[英]How in Linux bash how to check if script file exist and execute it in one liner
我在不同目錄中有許多腳本,我想檢查這些腳本文件是否存在,然后以最短的方式在一個內襯中執行它們。
有一個簡單的方法:
if [ -f /A/B/C/foo.sh ]; then /A/B/C/foo.sh
我可以縮短這支班輪嗎?
只需使用
/A/B/C/foo.sh
bash將檢查此腳本文件是否存在,然后執行它。 如果腳本不存在,它將報告
bash: /A/B/C/foo.sh: No such file or directory
或者,您可以通過以下方式禁止顯示錯誤消息:
/A/B/C/foo.sh 2> /dev/null
正如其他人建議的那樣,您也可以使用
[ -x /A/B/C/foo.sh ] && /A/B/C/foo.sh
請注意-x
而不是-f
(測試文件是否可執行)。
如果您在不同目錄中有許多腳本,則可以使用以下單行代碼執行它們:
for f in /A/B/C/foo.sh /D/E/F/bar.sh; do [ -x "$f" ] && "$f"; done
您可以使用如下功能:
run() { [[ -x $1 ]] && "$@"; }
然后將函數用作:
run '/A/B/C/foo.sh'
run '/A/B/C/bar.sh'
[ -f /A/B/C/foo.sh ] && /A/B/C/foo.sh
&&
是類似C的and
。 如果左側的命令返回true,請執行右側的命令。
嘗試bash 測試命令 :
以及它是如何工作的。
$ 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.