2

I am trying to just put bash commands into a variable and later run with exit code function.

command1="$(awk -v previous_date=$reply -f $SCRIPT_HOME/tes.awk <(gzip -dc $logDir/*) > $OUTFILE)" # Step 1

check_exit $command1 # Step2

Here it runs the command in step 1 and always returns 0 exit code.

How Can I put commands in a variable and later run with exit function.

3
  • 3
    Write a bash function? Commented Jul 31, 2014 at 10:07
  • @ n.m. - I've not done that, do you have any sample on this? Commented Jul 31, 2014 at 10:43
  • I am sorry, I did not understand "Write a bash function" . Sometime it happens, after saying you dont know you realize ohh boy i knew it. Thank you for your time Commented Jul 31, 2014 at 11:46

2 Answers 2

2

You can declare your function this way:

function command1 { 
    awk -v "previous_date=$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir"/*) > "$OUTFILE"
}

Or the older form:

command1() { 
    awk -v "previous_date=$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir"/*) > "$OUTFILE"
}

Take attention on placing variables inside double quotes to prevent word splitting and pathname expansion.

Some POSIXists would prefer that you use the old version for compatibility but if you're just running your code with bash, everything can just be a preference.

And you can also have another function like checkexit which would check the exit code of the command:

function checkexit {
    "$@"
    echo "Command returned $?"
}

Example run:

checkexit command1
Sign up to request clarification or add additional context in comments.

Comments

1

Try using a function:

do_stuff() { echo "$var"; echo that; }

You can later call this function and check the error code:

$ var="this"
$ do_stuff
this
that
$ echo $?
0

The variables defined in the global scope of your script will be visible to the function.

So for your example:

command1() { awk -v previous_date="$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir/*") > "$OUTFILE"); }

check_exit command1

By the way, I put some quotes around the variables in your function, as it's typically a good idea in case their values contain spaces.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.