Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put "> /dev/null 2>&1" into a variable?

Tags:

bash

How I wish it to work.

if [ $debug = 0 ]; then
   silent=""
else
   silent='> /dev/null 2>&1'
fi

#some command
wget some.url $silent

So in case $debug is set, it becomes

wget some.url > /dev/null 2>&1

Otherwise if $debug is not set to 1, it becomes

wget some.url

Storing "> /dev/null 2>&1" in a variable doesn't work. How can I do that?

like image 413
user28464 Avatar asked Dec 20 '22 02:12

user28464


1 Answers

This could be a good excuse to use a shell function:

silent() {
    "$@" > /dev/null 2>&1
}

Now you can silence programs by running them with:

silent wget some.url

If you want to only silence things conditionally, that's easy enough:

silent() {
  if [[ $debug ]] ; then
    "$@"
  else
    "$@" &>/dev/null
  fi
}
like image 157
Joni Avatar answered Jan 09 '23 19:01

Joni