Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How to run this script (called count.sh)?

awk 'BEGIN{ x=0 ; while (x < 5) { x+=1 ; print x ; } }'

I'm trying to run it with sh count.sh but it's giving me an error.

share|improve this question
4  
what error? Putting that alone in a text file and running sh count.sh works for me, though I'd prefer in general to use a shebang line, and possibly even an awk-only script... I still don't see why yours should generate an error, however. –  frabjous Feb 17 '11 at 16:03
1  
In general, if something is giving you an error, it's really helpful if you copy the exact error into your question. –  mattdm Feb 17 '11 at 16:11
    
Does it complain that awk was not found? :) –  alex Feb 17 '11 at 17:35
add comment

2 Answers

This is what I've done for my own scripts:

#!/usr/bin/awk -f
BEGIN{ x=0 ; while (x < 5) { x+=1 ; print x ; } }

The only drawback to this approach is that the path to Awk is hard-coded. This will break when the script is exported via NFS, and the NFS client has Awk installed in a different directory (say, /bin/awk versus /usr/bin/awk.)

Setting the executable permission will allow you to directly call the script, without having to use the shell to launch it (you can also leave off the .sh extension, since by convention scripts don't include them):

$ chmod +x count
$ ./count
1
2
3
4
5
share|improve this answer
1  
Regarding your #! line, you could use #!/usr/bin/env awk. I've seen it used for Python frequently. Wikipedia on #! portability –  jonescb Feb 18 '11 at 14:22
add comment

I ran you script, but I didn't get any error (although I expected to :) )

$ cat test.awk
awk 'BEGIN{ x=0 ; while (x < 5) { x+=1 ; print x ; } }'
$ bash test.awk
1
2
3
4
5

What error did you get? I expected awk will ask for an input file to process; learned a new thingie :)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.