Linux 的 Bash shell 裡面,若有一個字串需要執行,可以怎麼做呢?
Bash 執行「字串命令」的方法
Bash shell 要將此字串當 Shell 命令執行,可以有下述兩種作法:
- eval
- bash -c
- If the -c option is present, then commands are read from the first non-option argument command_string.
- If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters.
- The assignment to $0 sets the name of the shell, which is used in warning and error messages.
分別測試作法:(執行結果都一樣)
- eval "cd /; ls" # 執行完,帳號會在 / 的路徑上
- bash -c "cd /; ls" # 執行完,帳號還是在原始位置
- source <(echo "cd /; ls") # 感謝 typebrook 提供的作法