Why won't my bash script work?
First, you must add the "execute" permission bit. Using chmod +x
adds it, chmod -x
removes it.
Second, in Unix you must use the exact file name. If the file is named hello.sh
, you must run it by hello.sh
, not hello
. (You probably are used to Windows and its %PATHEXT%, which does not exist in Unix. Here, only the execute bit is considered and .sh
is meaningless to the system – the file can be named simply hello
if you want.)
Third, by default the current directory is not searched for commands (for security reasons). Either the script must be located in your $PATH, or you must run it by its full path name. Using .
(which means "the current directory") will suffice.
~/Desktop chmod +x hello.sh ~/Desktop ./hello.sh Hello, world! ~/Desktop ~/Desktop/hello.sh Hello, world! ~/Desktop
(./hello.sh
means "hello.sh
in the current directory".)
When you typed date
, you did not run your own script; you ran the system's date
command (just like you run the system's chmod
command when you type chmod
). The @
is not making a difference here.
The @
character simply indicates the presence of "extended metadata" associated with that file; most likely something specific to TextEdit. According to the ls
(1) manual page, you can use ls -l -@
(ls -l@
) to see the metadata.
Related videos on Youtube
punkrockbuddyholly
Updated on September 18, 2022Comments
-
punkrockbuddyholly over 1 year
I'm getting more comfortable with the terminal in Mac OSX and I thought I'd have a dabble at bash scripting. Not wanting to crawl before I could sit down I wanted to write an incredibly simple "Hello, world!" script so I did this:
~/Desktop touch hello.sh ~/Desktop vim hello.sh
I then added this to hello.sh
#!/bin/bash echo "Hello, world!"
I then did this:
~/Desktop chmod -x hello.sh ~/Desktop hello
At which point nothing happened.
I had downloaded an equally simple bash script from somewhere that was this:
#!/bin/bash echo "The current date and time." date
And when I did
~/Desktop date
it did exactly what it was supposed to.
So then I checked file permissions with ls -l and I got this:
-rw-r--r-- 1 Mike staff 33 5 Sep 21:13 hello.sh -rw-r--r--@ 1 Mike staff 50 5 Sep 21:00 date.sh
So clearly the @ is making all the difference, or so I thought. Instead of using vim I created the same file in TextEdit and after going through the same motions as before I ended up with the same situation, ie my script did nothing except now the permissions were showing an @ at the end of them.
So my questions are why is this not working, what am I doing wrong? And what is the @ at the end of the permissions?
-
punkrockbuddyholly over 12 yearsThank you very much, a perfect answer. It's working as I expect now.