0

I need to move file to a directory named after a parameter.

So far im stuck on how to moving file to the directory.

mkdir "$3"
cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 255 > $(shuf -n 1 /usr/share/dict/french)

So far this works but now I need to move this file to the directory user has specified in parameter $3. Ive tried with a find command selecting files created n seconds ago but this is really not efficient as it can select other files too.

2

You're creating a directory with the name from $3, but you're creating a file in the current directory.

To create the file in the new directory, just redirect to a name in that directory:

mkdir "$3"
tr -dc 'A-Za-z0-9' </dev/urandom | head -c 255 >"$3/$(shuf -n 1 /usr/share/dict/french)"

Or, to divide things up for readability:

dir=$3

mkdir -p -- "$dir" || exit 1

fname=$(shuf -n 1 /usr/share/dict/french)

tr -dc 'A-Za-z0-9' </dev/urandom | head -c 255 >"$dir/$fname"

Here, I've also made sure that if $3 contains a paths with subdirectories that does not exist, the full path is created (by adding -p to the call to mkdir; which also makes mkdir not fail if the path already exists). I'm also prefixing the path with -- just in case the first character in $3 is a - (this would otherwise confuse mkdir; -- signals the end of command line options). I'm also exiting with a non-zero exit status if the mkdir call failed.

  • Works perfectly, one question though, what happens if exit 1 is executed ? the rest of my script will not be executed ? – William Chrétien Apr 10 at 15:48
  • @WilliamChrétien That's correct. Failure in creating the output directory could possibly be handled somehow, but I don't know how in this example (only you could say what should happen then). It's common to exit 1 when a necessary command fails. The mkdir is necessary here because we would otherwise not have anywhere to store the output file. If the directory fails to be created, the rest of this particular script becomes a bit useless. – Kusalananda Apr 10 at 15:51
  • Great, for the context I now have to take the $4 parameter, divide it equally by $2 parameter (If it cant be divided equally, add spaces to fill last part) and put every part at the end of randomized file we just created (my main post). It looks like this: script.sh <word_src> <size_of_parts> <out_dir> <text_to_process>. The number of files created depends on how many divided parts of the $4 by $2 – William Chrétien Apr 10 at 15:56
  • @WilliamChrétien That's a new question :-) – Kusalananda Apr 10 at 15:59
  • Do I need to make a new post? Fairly new to this site – William Chrétien Apr 10 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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