eval を利用することで変数に格納されたコマンド文字列を実行することができる
以下のシェルスクリプトはコマンド「ls -l test.txt」を実行する
#!/bin/sh
commandString="ls -l test.txt"
eval $commandString
また、以下のシェルスクリプトは一度「ls -l test.txt」の実行結果を一度 result に格納したうえで echo で出力する
#!/bin/sh
commandString="ls -l test.txt"
result=$(eval $commandString)
echo $result
補足
eval はシェルの組み込みコマンドのためシェルの実装に依存する
POSIX で定められているためシェルがPOSIX互換であれば動きは同じになる
手元の bash で
help eval
を実行したところ以下のように表示された
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.