The file source inside the function accepts the parameters of the function.

I have one shell script that creates a second in the context of a function that takes parameters:

#!/bin/bash # bar.sh function f() { source foo.sh echo "Do something else with $1, after foo.sh is sourced." } f bar 

and

 #!/bin/bash # foo.sh x=${1:-"default"} echo $x 

The execution output is as follows:

 $ ./bar.sh bar Do something else with bar, after foo.sh is sourced. 

I expected to get default as the output of the first line instead of bar . It turns out that although I do not pass any arguments to foo.sh , it takes $ 1 from the context of the function f . I can understand this behavior by reading the bash documentation , but what would be the best way to override it?

+4
source share
1 answer

EDIT: based on your comment and edited question:

 #!/bin/bash # bar.sh function f() { # save $1 arg1="$1" # unset $1 shift # source your script; prints default source ./foo.sh # restore $1 set -- $arg1 # should print bar echo $1 echo "Do something else with $1, after foo.sh is sourced." } f bar 
+3
source

Source: https://habr.com/ru/post/1488656/


All Articles