Results 1 to 4 of 4

Thread: Bash script

  1. #1
    Join Date
    Jan 2013
    Beans
    3

    Bash script

    Hello,

    I have a very simple script that won't seem to work. Can someone please help.

    Code:
    #!/bin/bash
    
    DIR="/media"
    
    if[ 'ls $DIR | wc -l' -eq 0 ]; then
                   echo "No Drive"
    else
                   echo "Drive Found"
    fi
    And this is what I get when I run it.

    ./script: line 5: syntax error near unexpected token 'then'
    ./script: line 5: 'if[ 'ls $DIR | wc -l' -eq 0 ]; then'



    Thanks so much!

  2. #2
    Join Date
    May 2013
    Beans
    7

    Re: Help! Why won't this work?

    Between the start of if and the condition there should be a space and if you have to use a pipe (|), in the condition you have to enclose that with parenthesis and a dollar before the parenthesis.

    Here is the code:
    Code:
    #!/bin/bash
    
    DIR="/media"
    
    if [ $(ls $DIR | wc -l) -eq 0 ]; then
        echo "No Drive"
    else
        echo "Drive Found"
    fi
    I hope it helps you!

  3. #3
    Join Date
    Oct 2009
    Location
    Reykjavík, Ísland
    Beans
    11,247
    Distro
    Lubuntu 15.10 Wily Werewolf

    Re: Bash script

    Moved and renamed.
    About problems due to upgrading
    Bringing old hardware back to life.
    Please visit Quick Links -> Unanswered Posts

  4. #4
    Join Date
    Aug 2011
    Location
    47°9′S 126°43W
    Beans
    2,165
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: Bash script

    No need to make things more complicated than need:

    Code:
    ls /media/*
    if [[ $? -ne 0 ]] 
    then
       echo 'No media'
        ....
    or the terser

    Code:
    ls /media/* && { echo 'No media...' ; exit 1 ; }
    Last edited by ofnuts; May 28th, 2013 at 02:56 PM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •