我嘗試過以下命令
cut -c-11 ifshell.sh
cat ifshell.sh | cut -c-11 ifshell.sh
cat ifshell.sh | awk '{print $1} | cut -c-11 ifshell.sh
但每次我都得到 .sh 檔案的完整內容。這些命令在 .txt 檔案上完美運行。主要目標是提取腳本「#!/bin/bash」的前 11 個字符,以檢查該檔案是否確實是 bash bin 腳本。
答案1
您也可以使用標準 ̀file
指令:
[PRD][]user@localhost:~ 17:21:30
$ head -n 1 setproxymkt.sh
#!/bin/bash
[PRD][]user@localhost:~ 17:21:38
$ file setproxymkt.sh
setproxymkt.sh: Bourne-Again shell script, ASCII text executable
答案2
以下內容可能更適合您想要實現的目標:
# #// FILE could be a for-loop as well for example.
FILE="bash_scropt.sh" ;
if grep '#!/bin/bash' $FILE 1>/dev/null ; then
printf "$FILE bash-script\n" ;
else
printf "> $FILE -- NOT bash\n" ;
fi ;
您也可以將其與@netmonk建議混合使用,其中頭部的 grep 會更簡潔,例如:
FILE="bash_scropt.sh" ; if head -n 1 $FILE | grep '#!/bin/bash' 1>/dev/null ; then printf "$FILE bash-script\n" ; else printf "> $FILE -- NOT bash\n" ; fi