Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to run a script that's in a directory I have admin rights for, but I am trying to run it from somewhere that is not the directory.. I.E. its a generate load in script that reads all the files in the directory and it gives an output based on those files. But when I try to call it from the terminal it doesn't run unless active directory is the directory where the script is located, is this a permissions issue?

I have tried running it this way:

sh /path/to/file/FILE
./path/to/file/FILE

but when I cd to directory and run

./FILE

it runs fine.

Permissions for my account:

drwxrwxr-x 5 edennis edennis       4096 Nov 14 14:35 . 

Permissions for script:

-rwxrwxr-x 1 edennis edennis       3644 Nov 14 11:45 zScript

Permissions for files script is accessing:

-rw-rw-r-- 1 edennis edennis   10437424 Oct 15 10:27 document.txt

Contents of script:

#!/bin/bash

for file in *.txt

do

echo "this is my favorite file " "$file" >> output.txt;

done
share|improve this question
1  
Do you realize that sh /path/to/file/FILE and ./path/to/file/FILE aren't equivalent? First one will resolve path relatively to filesystem root (/), while second one will work relatively to current directory. Also, you can skip ./ if you're not running the script in a current directory. –  gronostaj Nov 14 '13 at 19:49

1 Answer 1

up vote 1 down vote accepted

The problem is that you still remain in the current directory when you run the script. So, the line

for file in *.txt

will expand the glob (*.txt) to all text files in your current directory. Of course, if your current directory (not the script's directory!) doesn't have any text files, you won't get any output.

If you want to change to the script's directory from within the script (which would make the *.txt glob work), see this Stack Overflow post: Can a Bash script tell what directory it's stored in?


While we're at it – don't forget to quote "$file" properly when you use to prevent a filename with spaces from breaking your commands. It doesn't matter in your case because echo doesn't care about the arguments, but it's a good habit to develop.

share|improve this answer

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.