Jenny Hilton
Jenny Hilton

Reputation: 1407

Script not working as Command line

i've created simple bash script that do the following :

#!/usr/bin/env bash
cf ssh "$1"

When I run the command line from the CLI like cf ssh myapp its running as expected, but when I run the script like

. myscript.sh myapp 

I got error: App not found

I dont understand what is the difference, I've provided the app name after I invoke the script , what could be missing here ?

update

when I run the script with the following its working, any idea why the "$1" is not working ...

#!/usr/bin/env bash
cf ssh myapp

Upvotes: 1

Views: 2003

Answers (1)

user4933750
user4933750

Reputation:

When you do this:

. myscript.sh myapp

You don't run the script, but you source the file named in the first argument. Sourcing means reading the file, so it's as if the lines in the file were typed on the command line. In your case what happens is this:

  • myscript.sh is treates as the file to source and the myapp argument is ignored.

  • This line is treated as a comment and skipped.

    #!/usr/bin/env bash
    
  • This line:

    cf ssh "$1"
    

    is read as it stands. "$1" takes the value of $1 in the calling shell. Possibly - most likely in your case - it's blank.

Now you should know why it works as expected when you source this version of your script:

#!/usr/bin/env bash
cf ssh myapp 

There's no $1 to resolve, so everything goes smoothly.

To run the script and be able to pass arguments to it, you need to make the file executable and then execute it (as opposed to sourcing). You can execute the script for example this way:

./script.bash arg1 arg2

Upvotes: 4

Related Questions