奇怪的 bash 語法錯誤取決於 sudo 的使用情況

奇怪的 bash 語法錯誤取決於 sudo 的使用情況

我創建了這個 bash 函數,透過檢查執行命令的用戶的 uid + 主目錄來檢測運行的用戶是否實際上以 root 用戶身份登錄,而不是使用 sudo:

#!/bin/bash

set -x
function check_root(){
  home=`sh -c 'cd ~/ && pwd'`
  if [ "$home" != "/root" ] || [ "$(id -u)" != "0" ]; then
    echo -e "This script can only be executed by the root user, not with sudo  elevation"
  exit 1
  fi
}

check_root

當我作為普通用戶(uid 1000)運行它時,它按預期工作:

++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/home/jake
++ '[' /home/jake '!=' /root ']'
++ echo -e 'This script can only be executed by the root user, not with sudo    elevation'
This script can only be executed by the root user, not with sudo elevation
++ exit 1

當我以 root 身份運行它時,它也按預期工作:

++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/root
++ '[' /root '!=' /root ']'
+++ id -u
++ '[' 0 '!=' 0 ']'

但是當我以普通用戶(uid 1000)身份使用 sudo 提升運行它時,我得到:

./check_root.sh: 4: ./check_root.sh: Syntax error: "(" unexpected

系統資訊:

Linux jake 3.11.0-26-generic #45~precise1-Ubuntu SMP 7 月 15 日星期二 04:02:35 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

bash --版本 GNU bash,版本 4.2.25(1)-release (x86_64-pc-linux-gnu)

答案1

我同時解決了這個問題,但尚未發布解決方案 - 結果與語法相關:

工作解決方案:

function check_root {
 stuff..
}

function check_root () {
 stuff..
}

例如,從函數宣告中刪除 () 或確保其兩側以空格分隔即可修復此問題。

這是我在 bash 線上說明頁中發現的內容,讓我發現了錯誤:

Shell Function Definitions
       A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters.  Shell functions are declared as follows:

       name () compound-command [redirection]
       function name [()] compound-command [redirection]
              This defines a function named name.  The reserved word function is optional.  If the function reserved word is supplied, the parentheses are optional

但是..我不知道在這種情況下到底是什麼讓 bash 表現得如此。

相關內容