Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

shell - Passing Command to Function in Bash

I am creating a setup bash script so I can quickly setup my servers.

Inside the run function I want to pass the command, which the run function will then verify whether is successful.

function run () {
    if output=$( $1 ); 
        then printf 'OK. (?%s?)
' "$output"; 
        else printf 'Failed! (?%s?)
' "$output"; 
    fi
}

printf 'Setting up ?uni? as system group...'

run " if [ ! $( getent group uni ) ]; 
          then sudo addgroup --system uni; 
          else echo 'Group exists.'; 
      fi "

However this results in a error: setup.sh: line 5: if: command not found

When I do this it works fine, but I want to eliminate repetitive code as I ha ve many commands:

if output=$(
    if [ ! $( getent group uni ) ]; then sudo addgroup --system uni; else echo 'Group exists.'; fi
); 
    then printf 'OK. (?%s?)
' "$output"; 
    else printf 'Failed! (?%s?)
' "$output"; 
fi

What am I doing wrong?

question from:https://stackoverflow.com/questions/65908369/passing-command-to-function-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The safe way to pass code to functions is... to encapsulate that code in another function.

run() {
  local output
  if output=$("$@"); then 
    printf 'OK. (?%s?)
' "$output"; 
  else
    printf 'Failed! (?%s?)
' "$output"; 
  fi
}

printf 'Setting up ?uni? as system group...'

step1() {
  if [ ! "$(getent group uni)" ]; then 
    sudo addgroup --system uni; 
  else
    echo 'Group exists.'; 
  fi
}

run step1

If your code didn't involve flow control operators (and otherwise fit into the definition of a "simple command"), you wouldn't even need to do that; with the above run definition (using "$@" instead of $1),

run sudo addgroup --system uni

...would work correctly as-is.


Using either eval or sh -c exposes you to serious security problems; see BashFAQ #48 for a high-level overview, and see BashFAQ #50 for a discussion of why code shouldn't be passed around as text (and preferred ways to avoid the need to do so in the first place!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...