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")"
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?