./ . 和#!/bin/bash 辨析Linux如何选择当前执行脚本的shell
最近遇到一個有趣的問題,讓我搞清楚Linux如何選擇當前執行腳本的shell
執行cts的的 media stress test 需要安裝?android-cts-media-1.0.zip
把這個文件解開,發現有一個?copy_media.sh 腳本,就是用 adb push 向 android devices 復制文件,很簡單的一個腳本,執行起來卻有錯
$./copy_media.sh 1920x1080
?
1920x1080 ./copy_media.sh: 22: [: 1920x1080: unexpected operator ./copy_media.sh: 25: [: 1920x1080: unexpected operator ./copy_media.sh: 28: [: 1920x1080: unexpected operator ./copy_media.sh: 31: [: 1920x1080: unexpected operator ./copy_media.sh: 34: [: 1920x1080: unexpected operator Usage: copy_media.sh [720x480|1280x720|1920x1080] [-s serial]for testing up to 1280x720, copy_media.sh 1280x720default resolution, when no argument is specified, is 480x360copy_media.sh all will copy all the files.
但如果我用
?
$. copy_media.sh 1920x1080
執行就沒有問題, 為何?我的猜想是:
./ 是用 /bin/sh 執行 copy_media.sh , 它比較”原始“,因此解釋不了 其中的 if [ ... ] 語句. ?用 . 就是在當前的 bash 下執行,所以成功了。
下面驗證我猜想是否正確
我用 $env | grep SHELL輸出是bash,那為何 copy_media.sh 是用 /bin/sh 執行
SHELL=/bin/bash
再看文件開始部分,真相大白,原來 copy_media.sh 指定用 /bin/sh執行
?
head copy_media.sh #!/bin/sh # Copyright (C) 2012 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
而用 . (就是 source 命令) 繞開了 #!/bin/sh;另一種方法是刪除這行,就會使用$SHELL變量執行的shell;當然改成 #!/bin/bash 也可以解決問題。
?
總結:
Linux 解釋腳本按使用 shell 的順序是
1) ?腳本第一行中 #!指定
2) 沒有指定就使用 $SHELL?
而使用 . 就是在當前 shell 中執行,當然就不會關注 !#/bin/sh 中的指定了.
?
轉載于:https://www.cnblogs.com/james1207/p/3313177.html
總結
以上是生活随笔為你收集整理的./ . 和#!/bin/bash 辨析Linux如何选择当前执行脚本的shell的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (读书笔记).NET大局观-.NET框架
- 下一篇: 软件工程期末考试复习(四)