bash脚本语法总结

1. 从一个脚本调用另一个脚本

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")


答案来源:https://stackoverflow.com/questions/8352851/shell-how-to-call-one-shell-script-from-another-shell-script

2. eval与exec

从 man bash 中查到

eval [arg ...]
The args are read and concatenated together into a single com‐
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval. If there are
no args, or only null arguments, eval returns 0.

 

exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process  (NOTE: exec分情况,有时候替换shell,有时候不替换)
is created. The arguments become the arguments to command. If
the -l option is supplied, the shell places a dash at the begin‐
ning of the zeroth argument passed to command. This is what lo‐
gin(1) does. The -c option causes command to be executed with
an empty environment. If -a is supplied, the shell passes name
as the zeroth argument to the executed command. If command can‐
not be executed for some reason, a non-interactive shell exits,
unless the execfail shell option is enabled. In that case, it
returns failure. An interactive shell returns failure if the
file cannot be executed. A subshell exits unconditionally if
exec fails. If command is not specified, any redirections take
effect in the current shell, and the return status is 0. If
there is a redirection error, the return status is 1.

 

3. ${} 和 $()

$():里面应该放命令

${}:里面放变量

$((算术式)):里面放算术式(NOTE:做算术表达式时必须用这个,否则会变成字符串连接)

资料来源:https://blog.csdn.net/weixin_42665725/article/details/116869527

 

在$()里面放命令,再用双引号包住$(),可以把命令的返回结果作为一个字符串进行其它操作

 #!/bin/bash
 marco(){
     echo "$(pwd)" > $HOME/marco_history.log
     echo "save pwd $(pwd)"
 }
 polo(){
     cd "$(cat "$HOME/marco_history.log")"
 }

 

 

 

 

 

 

 

 

 

 

 



posted @ 2022-02-21 22:11  yinhuachen  阅读(328)  评论(0编辑  收藏  举报