2015-06-03 46 views
0

我很難執行從文本文件中讀取的bash命令(帶有選項)。 在我的劇本有一個for循環讀取該文件中的命令,但出現了錯誤:使用文件中的選項執行bash命令

cat com.txt 
apt-get update 

我的腳本:

for i in `cat com.txt` ; do sudo bash -c $i ; done; 

顯示錯誤味精:

apt 1.0.1ubuntu2 for amd64 compiled on Oct 28 2014 20:55:14 
Usage: apt-get [options] command 
     apt-get [options] install|remove pkg1 [pkg2 ...] 
     apt-get [options] source pkg1 [pkg2 ...] 

apt-get is a simple command line interface for downloading and 
installing packages. The most frequently used commands are update 
and install. 

Commands: 
    update - Retrieve new lists of packages 
    upgrade - Perform an upgrade 
    install - Install new packages (pkg is libc6 not libc6.deb) 
    remove - Remove packages 
    autoremove - Remove automatically all unused packages 
    purge - Remove packages and config files 
    source - Download source archives 
    build-dep - Configure build-dependencies for source packages 
    dist-upgrade - Distribution upgrade, see apt-get(8) 
    dselect-upgrade - Follow dselect selections 
    clean - Erase downloaded archive files 
    autoclean - Erase old downloaded archive files 
    check - Verify that there are no broken dependencies 
    changelog - Download and display the changelog for the given package 
    download - Download the binary package into the current directory 

Options: 
    -h This help text. 
    -q Loggable output - no progress indicator 
    -qq No output except for errors 
    -d Download only - do NOT install or unpack archives 
    -s No-act. Perform ordering simulation 
    -y Assume Yes to all queries and do not prompt 
    -f Attempt to correct a system with broken dependencies in place 
    -m Attempt to continue if archives are unlocatable 
    -u Show a list of upgraded packages as well 
    -b Build the source package after fetching it 
    -V Show verbose version numbers 
    -c=? Read this configuration file 
    -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp 
See the apt-get(8), sources.list(5) and apt.conf(5) manual 
pages for more information and options. 
         This APT has Super Cow Powers. 
bash: update: command not found 

回答

2

在你的例子,你沒有執行整個行。你只需執行apt-get(它需要一個參數),然後執行update(這不是一個命令)。

只需使用的source在文件中,執行與(不需要執行位)bash命令:

source com.txt 
+0

喜混沌,我沒有完全得到你。我用下面的代碼編輯了for循環:for'in cat cat.txt';做源$我>> test.txt;完成;但是導致錯誤-bash:source:/ usr/bin/apt-get:無法執行二進制文件; -bash:update:沒有這樣的文件或目錄 – user3668330

+1

@ user3668330不,只有'source com.txt'沒有循環。 'source'逐行執行給定的文件,不需要循環。 – chaos

2

這其中的原因是多方面的not to read lines with cat in a for loop之一。改爲使用while read -r

while read -r cmd; do 
    sudo $cmd 
done <com.txt 

從你的例子中,bash -c似乎是多餘的,但是這取決於你的命令,以及在什麼特權您在sudoers成立。對於任何更復雜的事情,您可能會遇到http://mywiki.wooledge.org/BashFAQ/050source答案比可能的解決方法更有意義。

+0

感謝Chaos&tripleee。這非常有幫助:-) – user3668330