I'm messing around with scripting, I am able to create a script which when run prompts me for a name for a new dir, creates it then creates several files, echoes lines out, then deletes it all.
What I would like to do is morph it slightly so it creates and names the directory all by itself!
Seems a pointless exercise I know, but messing around with it is the best way I learn.
Here is my current script:
#!/bin/bash
echo "Give a directory name to create:"
read NEW_DIR
ORIG_DIR=$(pwd)
[[ -d $NEW_DIR ]] && echo $NEW_DIR already exists, aborting && exit
mkdir $NEW_DIR
cd $NEW_DIR
pwd
for n in 9 8 7 6 5 4 3 2 1 0
do
touch file$n
done
ls file?
for names in file?
do
echo This file is named $names > $names
done
cat file?
cd $ORIG_DIR
rm -rf $NEW_DIR
echo "Goodbye"
Instead of using the
read
command in order to get the value ofNEW_DIR
from the input, You can set hard-coded value for the NEW_DIR variable in the following way:replace the following line in your script:
with the following line:
If you want a surprise, instead of hardcoding the name you could use a technique to generate a random string, for example
This sets
NEW_DIR
to a string of eight alphanumeric characters. Every time you run the script, the new directory will have a different random name...Or to get a random word, pick a dictionary from
/usr/share/dict/
and useshuf
, for example:So
Instead of prompting for user input, you can hardcode values into scripts by using variable assignment operator (=). Thus, the following two lines,
can be replaced by a single line.
BTW, I know this is not relevant to the question but in the
for
loop you used in your script, you can write shorthand code for the range. Instead of9 8 7 6 5 4 3 2 1 0
, you may write it asYou could even go one step further: You could tell "read" to offer a proposition for the folder name, accept it by pressing return or change it as you like:
this would show a line:
To combine with the above suggestions, you could do the following:
Note that read -p "text" will prompt for the text and ask for the answer in the same line. If you want to stick to your code and have it ask for the 2-line-format you could do