Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Aug 2008
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Shell script problem

    Hi can someone tell me whats wrong with the following script i made:
    #!/bin/sh
    file1=$1
    file2=$2
    if [ $# = 2 && -e $file1]
    then
    if [ -e $file1 ]
    then
    echo "File 1 is" $file1
    echo "File 2 is" $file2
    cp $file1 $file2
    else
    echo "ERROR: File does not exist!"
    fi
    else
    echo "ERROR: Not enough command line arguments!"
    fi



    The problem is:

    philip@philip-laptop:~/Desktop$ sh copy.sh test.java test2.java
    [: 16: missing ]
    ERROR: Not enough command line arguments!


  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    The reason is most likely that $# is 3 not 2 because the name of the script is passed in as the first command line argument. Echo out $# and see.
    OracleGuy

  • #3
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by philmetz View Post
    Hi can someone tell me whats wrong with the following script i made:
    #!/bin/sh
    file1=$1
    file2=$2
    if [ $# = 2 && -e $file1]
    then
    if [ -e $file1 ]
    then
    echo "File 1 is" $file1
    echo "File 2 is" $file2
    cp $file1 $file2
    else
    echo "ERROR: File does not exist!"
    fi
    else
    echo "ERROR: Not enough command line arguments!"
    fi



    The problem is:

    philip@philip-laptop:~/Desktop$ sh copy.sh test.java test2.java
    [: 16: missing ]
    ERROR: Not enough command line arguments!

    why don't you use cp -i ?

    Quote Originally Posted by oracleguy View Post
    The reason is most likely that $# is 3 not 2 because the name of the script is passed in as the first command line argument. Echo out $# and see.
    no, $# is 2 not 3, 'program name' is not counted here

    best regards

  • #4
    Regular Coder brad211987's Avatar
    Join Date
    Sep 2005
    Location
    Ohio
    Posts
    631
    Thanks
    10
    Thanked 50 Times in 50 Posts
    at this line:

    Code:
    if [ $# = 2 && -e $file1]
    do you need a space near the end to make it $file1 ] ?

    Its been quite a while since I've done any shell scripting, but I do remember it being picky.


  •  

    Posting Permissions

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