Why doesn't echo $1 print $1 in this simple bash script?
#!/bin/bash
# function.sh
print_something () {
echo $1
}
print_something
$ ./function.sh 123 -> why doesn't it print '123' as a result?
Why doesn't echo $1 print $1 in this simple bash script?
#!/bin/bash
# function.sh
print_something () {
echo $1
}
print_something
$ ./function.sh 123 -> why doesn't it print '123' as a result?
Positional parameters refer to the script's arguments in the main level of the script, but to function arguments in function body. So
print_something Something
would actually print Something.
If you want to pass the script's arguments to a function, you must do that explicitly. Use
print_something "$1"
to pass the first argument, or
print_something "$@"
to pass all of them, though the function in example only uses the first one.
"$@" to print_something, as it's currently written, would still only print the first of the arguments though.
"$*" would be a single string (joined on the first character of $IFS) while "$@" would be a list of individually quoted elements.
"$@", even if in this case there is only one such parameter, is to cover all such cases. If the OP decides to add a second parameter, there's nothing to change in the function invocation. And everyone else who reads this will learn the right way to do it to avoid having to re-do it later, too.
This is because a called function gets its own set of positional parameters, independent of the parent's / caller's set. Try
print_something "$1"
(and echo "$1", or even better printf '%s\n' "$1", remember to quote parameter expansions and that echo can't be used for arbitrary data).
$1 is generally different from the function's $1, although they CAN become the same if used like proposed above. If I get you right, the echo can stay the same (echo $1) when the function is called with single parameters (print_something $2 takes the caller's $1 and "makes" it $1 inside the function)
echo $1 doesn't make sense unless you want $1 to be treated as a $IFS-delimited list of file patterns to expand. echo "$1" would make more sense, though would not output the content of $1 for values of $1 like -nene, -EE...