[英]How in Linux bash how to check if script file exist and execute it in one liner
I have many scripts in different directories , i want to check if those script file exist and then execute them in one liner in shortest way . 我在不同目录中有许多脚本,我想检查这些脚本文件是否存在,然后以最短的方式在一个内衬中执行它们。
there is the simple way : 有一个简单的方法:
if [ -f /A/B/C/foo.sh ]; then /A/B/C/foo.sh
can i shorten this one liner ? 我可以缩短这支班轮吗?
Simply use 只需使用
/A/B/C/foo.sh
The bash will check if this script file exists and then execute it. bash将检查此脚本文件是否存在,然后执行它。 If the script does not exist, it will report
如果脚本不存在,它将报告
bash: /A/B/C/foo.sh: No such file or directory
Alternatively, you can suppress the error message with 或者,您可以通过以下方式禁止显示错误消息:
/A/B/C/foo.sh 2> /dev/null
As others suggested, you can also check the script existence on your own using 正如其他人建议的那样,您也可以使用
[ -x /A/B/C/foo.sh ] && /A/B/C/foo.sh
Note the -x
instead of -f
(tests if the file is executable). 请注意
-x
而不是-f
(测试文件是否可执行)。
If you have many scripts in different directories, you can execute them using the following one-liner: 如果您在不同目录中有许多脚本,则可以使用以下单行代码执行它们:
for f in /A/B/C/foo.sh /D/E/F/bar.sh; do [ -x "$f" ] && "$f"; done
You can use a function like this: 您可以使用如下功能:
run() { [[ -x $1 ]] && "$@"; }
And then use function as: 然后将函数用作:
run '/A/B/C/foo.sh'
run '/A/B/C/bar.sh'
[ -f /A/B/C/foo.sh ] && /A/B/C/foo.sh
The &&
is a C-like and
. &&
是类似C的and
。 If the command on the left return true, execute the command on the right. 如果左侧的命令返回true,请执行右侧的命令。
Try bash test command : 尝试bash 测试命令 :
And how it's works. 以及它是如何工作的。
$ cat src.sh
echo "Test test"
//if src.sh exist
$test -e src.sh && sh src.sh
Test test
// if not, src.sh not run
$test -e src1.sh && sh src.sh
是的,可以使用速记格式将其进一步缩短:
[ -f /A/B/C/foo.sh ] && /A/B/C/foo.sh || echo "script not found"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.