简体   繁体   中英

Writing .sh code

I have never written .sh code so sorry if this question seems too obvious:

I have an executable 'executable1' that I run in the ubuntu console as follows: ./executable1 fileName1

This works perfectly.

Considering that I have a lot of files on which I need to run this code (1000), I wrote a sh script where I stocked all the file names and tried to make executable1 work on them as follows:

#!/bin/bash
filesNames=(fileName1 fileName2 [etc] fileName1000)
numberFiles=1000;
for i in `seq 1 $numberFiles`
do
  ./executable1 ${filesNames[$i]} > results.txt &
done

I run the code (named scriptName.sh) in my shell like this:

bash scriptName.sh 

However, I get the following error:

./executable1: No such file or directory

I don't understand, since when I execute ./executable1 in the shell alone, it worked perfectly...

After the line

numberFiles=1000;

write this

cd /dir/of/the/executable

so the bash can find the executable.

maybe easier way is:

for ii in `ls <path_to_dir_with_1000_files>` ; 
   do
      /dir/of/the/executable/executable1 $ii ;
   done

...you put a list of those 1000 into $ii array and using for you execute executable1 for every item from $ii array. Execute this script from directory where you have mentioned 1000 files.

I would further simplify to:

for ii in /path/to/files/*; do
    ./executable1 "$ii" >> results.txt
done

The ">>" is important because you don't want to overwrite the whole results.txt. Also, don't try to background the task ("&") because you will have a thousand processes running at the same time, and this will at the very least clobber results.txt and maybe also crash your computer.

But to answer your question, all the paths (the script you want to run, executable1, and the files) to executable1 are relative to where you're running the script. So if you're in ~/Documents but the executable1 and script are in ~/bin, and the files are in ~/Documents/Data, you need to run ~/bin/script, and script needs to reference "~/bin/executable1" and "~/Documents/Data/*". It's a bad idea to write relative paths in scripts (./foo, ../../foo/bar) unless you know exactly where the user will be when he runs the script. For example, a "rename-to-upper-case" script could assume you want to operate on all files in the current directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM