由 neevop 十二月 6, 2022
Functions
Defining functions
myfunc() {
echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc() {
echo "hello $1"
}
myfunc "John"
Returning values
myfunc() {
local myresult='some value'
echo "$myresult"
}
result=$(myfunc)
Raising errors
myfunc() {
return 1
}
if myfunc; then
echo "success"
else
echo "failure"
fi
Arguments
Expression | Description |
---|---|
$# |
Number of arguments |
$* |
All positional arguments (as a single word) |
$@ |
All positional arguments (as separate strings) |
$1 |
First argument |
$_ |
Last argument of the previous command |
Note: $@
and $*
must be quoted in order to perform as described.
Otherwise, they do exactly the same thing (arguments as separate strings).
See Special parameters.
Redirection
python hello.py > output.txt # stdout to (file)
python hello.py >> output.txt # stdout to (file), append
python hello.py 2> error.log # stderr to (file)
python hello.py 2>&1 # stderr to stdout
python hello.py 2>/dev/null # stderr to (null)
python hello.py >output.txt 2>&1 # stdout and stderr to (file), equivalent to &>
python hello.py &>/dev/null # stdout and stderr to (null)
echo "$0: warning: too many users" >&2 # print diagnostic message to stderr
python hello.py < foo.txt # feed foo.txt to stdin for python
diff <(ls -r) <(ls) # Compare two stdout without files
printf
printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga
printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"
printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000"
printf '%s\n' '#!/bin/bash' 'echo hello' >file
# format string is applied to each group of arguments
printf '%i+%i=%i\n' 1 2 3 4 5 9
Heredoc
cat <<END
hello world
END
Reading input
echo -n "Proceed? [y/n]: "
read -r ans
echo "$ans"
The -r
option disables a peculiar legacy behavior with backslashes.
read -n 1 ans # Just one character
Check for command’s result
if ping -c 1 google.com; then
echo "It appears you have a working internet connection"
fi