I am invoking a script through source
command and want to pass arguments to the script.
I have checked man source
, the bash returns:
: [arguments]
No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.source filename [arguments]
Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.
It has no examples, so I don't understand it .
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.
Using arguments Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1 , $2 , and so on. The $0 will contain the script name.
In Linux systems, source is a built-in shell command that reads and executes the file content in the current shell. These files usually contain a list of commands delivered to the TCL interpreter to be read and run.
Arguments can be passed to a bash script during the time of its execution, as a list, separated by space following the script filename. This comes in handy when a script has to perform different functions depending on the values of the input.
Create a file test.sh
with the following contents:
echo "I was given $# argument(s):" printf "%s\n" "$@"
and then source it from an interactive shell session:
$ source ./test.sh a 'b c' I was given 2 argument(s): a b c
so you access the arguments just like you would do in a regular bash script, with $@
or $1
, $2
, $3
, etc.
For comparison, run it as a regular script:
$ bash ./test.sh a 'b c' I was given 2 argument(s): a b c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With