0

I'm new to Linux and would like to create a new directory based on the user's input for the folder name. How can I also create a new directory, inside the first directory by asking for a name from the user again?

Code:

#! /bin/bash
echo "Enter name of dir":
read folder1
mkdir -p $folder1
touch docu.dat
chmod 755 docu.dat

I try to see the list of directory that was created with the command ls, but I did not see the list, and I wonder why. I also want to know how I should execute the script file using bash parameters. Please help me correct it.

terdon
  • 242,166
amada
  • 3
  • 2
  • 1
    Please [edit] your question and add a bit more detail. If you want to ask for a name again, why don't you just do the same thing (echo "Enter another name:"; read folder2)? What else is missing? And what do you mean by "execute the script using bash parameters"? Do you mean pass the directory names as arguments to the script instead of asking the user for input? – terdon Jun 25 '21 at 08:55
  • @terdon It's just an activity and it instruct to name a directory the using user input then create another one inside it and name it again using user input , then execute a bash parameters which I'm not familiar. I just want to know how to do it correctly because I'm unfamiliar with some of the commands. – amada Jun 25 '21 at 09:01

1 Answers1

1

If you want to ask the user for a second name, just ask the user for a second name:

#! /bin/bash
echo "Enter name of dir":
read folder1
echo "Enter name of sub-dir":
read folder2
mkdir -p -- "$folder1/$folder2"
touch docu.dat
chmod 755 docu.dat

Although I suspect that you want to create docu.dat inside the directory you just made, in which case you'd want this:

#! /bin/bash
echo "Enter name of dir":
read folder1
echo "Enter name of sub-dir":
read folder2
mkdir -p -- "$folder1/$folder2"
touch -- "$folder1/$folder2"/docu.dat
chmod 755 -- "$folder1/$folder2"/docu.dat

However, as a general rule, try to avoid prompting the user for input. That makes the script very hard to automate, very hard to re-run, it is easy for a user to enter a wrong value etc. Instead, take the directory names as arguments:

#! /bin/bash
dirName="$1/$2";
mkdir -p -- "$dirName"
touch -- "$dirName"/docu.dat
chmod 755 -- "$dirName"/docu.dat

And then run the script like this:

./script.sh "dir1" "dir2"

The -- are there so that your script can also handle directory names starting with a -. See What does "--" (double-dash) mean?.

terdon
  • 242,166