0

I am new to UNIX and shell programming. I am trying to make a command lines text file executable by using chmod command.

Below are the codes:

$ls
a  aa  aba  chapt1  chapt2  chapt3  newprog
$filename=ch
$cat newprog
echo a?* n* ${filename}*
$chmod +x newprog
$ls -l newprog
-rwxr-xr-x 1 xxxxx xxxxx 25 Apr 12 09:50 newprog

But when I execute newprog by

newprog

I got

newprog: command not found

I create newprog by using vi command and I am using putty. Which part did I do wrong?


Thanks to Benjamin W. By using ./newprog, the file is executable.

But the result is

aa aba newprog a aa aba chapt1 chapt2 chapt3 newprog

I think the result that I expect is

aa aba newprog chapt1 chapt2 chapt3

Why there are duplicates?

NewGuyComesIn
  • 189
  • 1
  • 2
  • 14
  • 3
    If it's not in your path, you have to call it `./newprog` if you're in the same directory, or with the complete path. – Benjamin W. Apr 12 '16 at 15:15
  • You should also add a 'shebang' to the top of your file. https://stackoverflow.com/questions/8779951/how-do-i-run-a-shell-script-without-using-sh-or-bash-commands – dmb Apr 12 '16 at 15:17
  • See here for explanations: http://unix.stackexchange.com/questions/4430/why-do-we-use-to-execute-a-file – Benjamin W. Apr 12 '16 at 15:21
  • @BenjaminW. Thanks. It makes the file executable. But the result is odd. – NewGuyComesIn Apr 12 '16 at 15:24
  • If your immediate problem was fixed, what you have is a new question. Editing your old question to make it a new and different question is frowned on if there are already answers -- if you have a new and different question, it should be asked separately. – Charles Duffy Apr 12 '16 at 15:37
  • See http://meta.stackoverflow.com/questions/290746/follow-on-question-vs-edit-to-original-when-to-use-which for the official policy question/answer on this topic. – Charles Duffy Apr 12 '16 at 15:39
  • @CharlesDuffy Thanks for this. I will keep it in mind. – NewGuyComesIn Apr 12 '16 at 15:42

1 Answers1

2

For security reasons UNIX does not directly execute files in the current directory but only from directories found in the PATH. This is to avoid an attack where somebody puts a malicious executable file with the same name as an often used command into a writeable directory and hopes that somebody executes it with his rights. For the same reason you should also not put . into the PATH.

If you are sure you want to execute such a file use ./filename.

To answer the extended question: since filename was not exported the value the script sees is empty. The last pattern is therefore * which matches all files (that don't start with a dot).

To get your expected result do export filename (this tells the shell to put the filename variable into the environment given to child processes) and run the script again.

Henry
  • 42,982
  • 7
  • 68
  • 84