Dipankar Deka Dipankar Deka - 6 months ago 35
Bash Question

File inside a directory script

I have written a bash script to create a file in the directory name given. The script I wrote was:

D=$2
F=$1
D=`cat > "$F" && mkdir -v "$D"`


When I run the script passing the 2 arguments filename and pathname, it shows the file as being created but when I search for that file it not showing up in that directory.

Answer

Your order or creation is wrong, use something like this:

~/temp5$ ls
script1.bash
~/temp5$ cat script1.bash 
D=$2
F=$1
mkdir -v "$D" && > "$D/$F"
~/temp5$ ./script1.bash newfilename newdirname
mkdir: created directory ‘newdirname’
~/temp5$ ls
newdirname  script1.bash
~/temp5$ ls newdirname/
newfilename
$

This is the final script:

D=$2
F=$1
mkdir -v "$D" && > "$D/$F"

Edit1:

$ ls
script.bash
~/temp5$ cat script.bash 
D=$2
F=$1
[[ "$D$F" =~ ^[a-zA-Z0-9]+$ ]] && mkdir -v "$D" && > "$D/$F"
~/temp5$ ./script.bash newfile123 newdir123
mkdir: created directory ‘newdir123’
~/temp5$ ls
newdir123  script.bash
~/temp5$ ls newdir123/
newfile123
~/temp5$ ./script.bash 'newfile;123' newdir123
~/temp5$ ./script.bash newfile.123 newdir123
~/temp5$ ls
newdir123  script.bash
~/temp5$ ls newdir123/
newfile123
$

This is the final script:

D=$2
F=$1
[[ "$D$F" =~ ^[a-zA-Z0-9]+$ ]] && mkdir -v "$D" && > "$D/$F"

[[ "$D$F" =~ ^[a-zA-Z0-9]+$ ]] ensures that both directory and file names have only these(1 or more alphanumeric/numeric) characters: a-z, A-Z and 0-9 using regular expressions.