sudo の使用状況に応じて発生する奇妙な bash 構文エラー

sudo の使用状況に応じて発生する奇妙な bash 構文エラー

コマンドを実行しているユーザーの uid + ホーム ディレクトリをチェックして、実行中のユーザーが実際に root ユーザーとしてログインしていて sudo を使用していないかどうかを検出するために、この bash 関数を作成しました。

#!/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 ']'

しかし、sudo 昇格を使用して通常のユーザー (uid 1000) として実行すると、次のようになります。

./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 --version 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 がなぜこのように動作するのかは正確にはわかりません。

関連情報