我制作了一個 bash 腳本。它讀取一個包含命令串列的檔案并運行每個命令。
命令串列如下所示。
ENV_NUMBER=1 command1
ENV_NUMBER=2 command2
ENV_NUMBER=3 command3
每行在命令之前都有一個環境變數,用于為命令設定相同的名稱但不同的值。
腳本如下所示。
while read line
do
if [ -n $line ] ; then
# run command in background
$line &
fi
done < comandlist.txt
我預計:
- 使用 ENV_NUMBER=1 運行 command1
- 使用 ENV_NUMBER=2 運行 command2
- 使用 ENV_NUMBER=3 運行 command3
但是,我運行了腳本然后我得到了錯誤:
ENV_NUMBER=1: command not found
我如何解決它?
uj5u.com熱心網友回復:
有關決議簡單命令的順序的說明,請參見https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01 。基本上,在步驟 1 中,檢查該行的變數分配。由于此時的簡單命令只是“$line”,因此沒有變數賦值。然后,在步驟 2 中,$line擴展為“ENV_NUMBER=1 command1”,并將第一個欄位作為命令。不再掃描該行以查找變數分配,并將字串ENV_NUMBER=1作為要執行的命令。
聽起來好像您想評估字串“$line”,在這種情況下,您需要做eval "$line"的不僅僅是執行$line. 但請注意“eval 是邪惡的”常識。像這樣使用eval通常被認為是不好的做法。
uj5u.com熱心網友回復:
從命令檔案內部看,您的邏輯看起來不錯...
請參閱https://www.gnu.org/software/bash/manual/bash.html#Simple-Command-Expansion
問題是您正在將變數賦值加載到變數中,將其呈現為資料而不是命令,然后嘗試將其背景關系破解。
ENV_NUMBER=1 command
不一樣
"ENV_NUMBER=1" "command"
這就是你正在有效地做的事情。
試試這個。
sed -Ei 's/$/\&/' comandlist.txt # make sure there are no blank lines first!
然后要么
chmod x comandlist.txt
./comandlist.txt
要么
source comandlist.txt
這使得comandlist.txt腳本與 & 符號一起完成,否則它已經是。您的程式將其作為資料讀入,然后嘗試將其轉換回腳本一次一行。不要那樣做。
cf https://mywiki.wooledge.org/BashFAQ/050
原始答案 - 供參考
你確定你使用的是bash嗎?
你有像#!/bin/bash你腳本的第一行這樣的東西嗎?
這是我的簡單示例腳本:
$: cat y
#! /bin/bash
echo "x=[$x]" # using whatever is available, not setting in the script
毫無價值地運行它x:
$: unset x; ./y # nothing to show, x has no value
x=[]
用一組運行它x:
$ x=foo; ./y # NOT exported to the subshell! Can't see it.
x=[]
在命令本身中臨時顯式設定它:
$: x=foo ./y # this creates x in this subshell, goes away when it ends
x=[foo]
再次運行而不設定顯示它是臨時的......
$ ./y # didn't keep from last run
x=[]
在父環境中顯式匯出:
$: export x=bar; ./y # reads the exported value from the parent
x=[bar]
通過從命令列提供一個臨時值來手動覆寫匯出的值:
$: x=foo ./y # overrides exported value of "bar" in the subshell *only*
x=[foo]
使用仍然匯出的值再次運行,無需特殊編輯:
$: ./y # x still exported as "bar"
x=[bar]
So obviously what you are doing works fine in bash.
As I mentioned above, maybe you are not using bash.
Make sure you have a shebang. #! have to be the very first two characters in the file for it to work - no spaces above or before, no comments, nothing.
Let us know if that doesn't help.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/449534.html
