為什麼在這種特定情況下我不必引用字元串變數?
我的基於 Ubuntu/Debian 的 Linux 更新 POSIX shell 腳本似乎要求我不要用正在執行的儲存命令對字元串變數**進行雙引號。**由於我不明白這個問題,我想問這是為什麼?如果程式碼是正確的呢?
警告:SC2086,wiki,“雙引號以防止萬用字元和分詞。”
腳本如下,有問題的部分突出顯示:
#!/bin/sh # exit script when it tries to use undeclared variables set -u # color definitions readonly red=$(tput bold)$(tput setaf 1) readonly green=$(tput bold)$(tput setaf 2) readonly yellow=$(tput bold)$(tput setaf 3) readonly white=$(tput bold)$(tput setaf 7) readonly color_reset=$(tput sgr0) # to create blocks of texts, I separate them with this line readonly block_separator='----------------------------------------' step_number=0 execute_jobs () { while [ ${#} -gt 1 ] do job_description=${1} job_command=${2} step_number=$(( step_number + 1 )) printf '%s\n' "Step #${step_number}: ${green}${job_description}${color_reset}" printf '%s\n' "Command: ${yellow}${job_command}${color_reset}" printf '%s\n' "${white}${block_separator}${color_reset}" # RUN THE ACTUAL COMMAND # ShellCheck warns me I should double quote the parameter # If I did, it would become a string (I think) and I'd get 'command not found' (proven) # As I don't understand the issue, I left it as I wrote it, without quotes ### shellcheck disable=SC2086
**``` if sudo ${job_command} # <– HERE
then printf '\n' else printf '%s\n\n' "${red}An error occurred.${color_reset}" exit 1 fi shift 2
done }
execute_jobs
‘configure packages’ ‘dpkg –configure –pending’
‘fix broken dependencies’ ‘apt-get –assume-yes –fix-broken install’
‘update cache’ ‘apt-get update’
‘upgrade packages’ ‘apt-get –assume-yes upgrade’
‘upgrade packages with possible removals’ ‘apt-get –assume-yes dist-upgrade’
‘remove unused packages’ ‘apt-get –assume-yes –purge autoremove’
‘clean up old packages’ ‘apt-get autoclean’
**你不能在這裡引用變數:
if sudo ${job_command}
因為你確實想要分詞。如果您引用,則命令變為(對於您的第一步)
if sudo "dpkg --configure --pending"
並
sudo
查找 commanddpkg --configure --pending
,而不是dpkg
帶有參數的 command--configure
和--pending
,如其錯誤消息所示:sudo: dpkg --configure --pending: command not found
(嘗試使用額外的空格使其更明確)。
省略引號後,shell 會拆分參數,一切都按預期工作。**