1

When i run this command it still outputs the same message when nothing is in the waste bin directory, how could I get the command to output a different message when there are no files in the bin?

            #! /bin/bash
            #! listwaste - Lists the names of all the files in your waste bin and their size
            #! Daniel Foster 23-11-2015

            echo "The files that are in the waste bin are:"

            ls -1 ~/bin/.waste/

I know this should be simple but I'm just starting out and I am guessing i should be using an if statement or something similar.

Thanks for the help in advance.

0

Oneliner:

trash() { ls -1 ~/bin/.waste; }; [[ $(trash | wc -l) -eq 0 ]] && echo no waste || echo -e "waste:\n$(trash)"

Better formatted:

trash() { ls -1 ~/bin/.waste; }
[[ $(trash | wc -l) -eq 0 ]] && echo no waste || echo -e "waste:\n$(trash)"

Nerd formatted:

#!/bin/bash

function trash() {
  ls -1 ~/bin/.waste
}

if [[ $(trash | wc -l) -eq 0 ]]; then
  echo 'There are no files in the waste bin.'
else
  echo 'The files that are in the waste bin are:'
  trash
fi

All 3 examples are performing the exact same functionality, only formatted differently, depending on preference.

If you want to actually be able to run the command listwaste, then put this in a script named listwaste, make sure you make it executable (chmod +x), and save the script in a directory that is listed in your $PATH. You can echo $PATH to see these directories that contain executables that you will be able to call directly from the shell.

1

Assign the output to a variable, behave different-like, depending:

$ mkdir ~/bin/.waste
$ OUTPUT=$( ls -1 ~/bin/.waste )
$ if [[ -z "$OUTPUT" ]]; then echo no waste; else echo $OUTPUT; fi
no waste
$ touch ~/bin/.waste/blkasdjf
$ OUTPUT=$( ls -1 ~/bin/.waste )
$ if [[ -z "$OUTPUT" ]]; then echo no waste; else echo $OUTPUT; fi
blkasdjf
$ 
  • You don't have to put spaces in between your command variable parentheses, and you don't have to quote variables when they are in double-brackets. You should also double-quote the OUTPUT= variable command ("$(ls -1 ~/bin/.waste)") so that spacing is preserved accurately. Also, it's not a good practice to create Bash variables in all caps. Ideally, it should read output="$(ls -1 ~/bin/.waste)". – rubynorails Nov 23 '15 at 23:13
0
file_count=$(ls -1 ~/bin/.waste | wc -l)
if [[ $file_count == 0 ]]; then
    echo "There are no files in the waste bin"
else
    echo "The files that are in the waste bin are:"
    ls -1 ~/bin/.waste
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.