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?
Best Answer
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 byhello.sh
, nothello
. (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 simplyhello
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.(
./hello.sh
means "hello.sh
in the current directory".)When you typed
date
, you did not run your own script; you ran the system'sdate
command (just like you run the system'schmod
command when you typechmod
). 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 thels
(1) manual page, you can usels -l -@
(ls -l@
) to see the metadata.