How to use mkdir for nested directories [duplicate] - bash

This question already has answers here:
How to manually expand a special variable (ex: ~ tilde) in bash
(19 answers)
Closed last month.
I have the following variable that shows where I should write my report to
REPORT="ZFS(~/Q4Y22/report/q4y22.md)"
I have used sedto extract the path and dirname command to get the
~/Q4Y22/report/dir name which I assign to reportdir variable.
However when I run the following test, instead of the Q4Y22 dir being created in my home dir, it literally creates the following directory hierachy ~/Q4Y22/report inside my home for example farai/~/Q4Y22/report instead of farai/Q4Y22/report
if [ -d $reportdir ]
then
echo "dir exists, keep moving"
else
mkdir -p $reportdir
fi
How do I get around this, I tried using sed to remove the tilde from the path but i was wondering if there is a more clever way

My try on this:
#!/bin/bash
REPORT="~/Q4Y22/report/q4y22.md"
reportdir=$(dirname "${REPORT/'~'/$HOME}")
if [ -d "$reportdir" ]
then
echo "dir exists, keep moving"
else
mkdir -p "$reportdir"
fi
This is a bit fragile since you could have ~ in the filename, though, but you could improve this script to replace only the first char if it's a tilde.

Related

Bash script get absolute path [duplicate]

This question already has answers here:
How do you normalize a file path in Bash?
(24 answers)
Difference between sh and Bash
(11 answers)
Closed last year.
I'm not familiar with bash scripting. In my app, I have three folders. Frontend, backend, and script are the three folders. My bash script is contained within the script. This is the structure of my app Image. I'd like to retrieve absolute path variables (frontend and backend) from my script. I'm not sure what to do. I was successful in obtaining the script path folder. My objective is to obtain an absolute route from a script.
#!/bin/sh
root_path="$( cd "$(dirname "$0")" >/dev/null 2>&1 || exit ; pwd -P )"
#frontend_path=
#backend_path=
echo "Getting absolute path ${root_path}"
Adding /.. after the output of dirname should do the trick to get you the root path:
root_path="$( cd "$(dirname "$0")/.." >/dev/null 2>&1 || exit ; pwd -P )"
From that on, you can just add /frontend / /backend to get the other paths:
frontend_path="$root_path/frontend"
backend_path="$root_path/backend"

Need to check if .gz files exist in a directory [duplicate]

This question already has answers here:
How do I tell if a file does not exist in Bash?
(20 answers)
Closed 6 years ago.
I have a prompt in my shell script where the user can choose a directory. I am trying to make it so that if a .gz file exists in that directory, they exit the loop, and if not, the user is asked again to choose a directory, but it just isn't working. Here's what I have so far:
ls -d */
while :
do
echo "Which Directory do you want to access?"
read input_variable1
cd $input_variable1
if [ CHECK FOR .gz ]
then
break
else
ls -d */
echo "no .gz files to unzip. Try again."
fi
done
Test supports using wildcards, so [ -f *.gz ] will be true if there is one file matching *.gz (and false otherwise - as #tripleee pointed out, this will fail with multiple matches; see below for a better variant).
Another possibility is to use if ls *.gz &>/dev/null; then ...; else ...; fi (which will not throw any errors).

Bash make and open directory [duplicate]

This question already has answers here:
One command to create and change directory
(9 answers)
Closed 7 years ago.
Let's say I have the following command:
mkdir directory && cd directory
I normally do this a lot during the day so I'm wondering if there is a simpler shorter way of doing this.
Does anybody know?
you can call last argument by &_
mkdir directory && cd $_
this is result
system:/tmp # mkdir directory && cd $_
system:/tmp/directory #
Put the following code in your ~/.bashrc or ~/.zshrc :
mkcd () {
mkdir "$1"
cd "$1"
}
Then in your shell, enter the following command mkcd foo. As you can see, this function need one argument which are the name of the directory.

How to set a Directory as an Argument in Bash

I am having trouble finding out how to set a directory as an argument in bash.
The directory I am trying to have as an argument is /home/rrodriguez/Documents/one.
Anywhere I try to look for an answer I see examples like dir = $1 but I cant seem to find an explanation of what this means or how to set it up so that it references my specific file location. Could anyone show me how to set up my variable for my path directory?
Adding my code for a better understanding of what im trying to do:
#!bin/bash
$1 == 'home/rrodriguez/Documents/one/'
dir = $1
touch -c $dir/*
ls -la $dir
wc$dir/*
Consider:
#!bin/bash
dir=$1
touch -c "$dir"/*
ls -la "$dir"
This script takes one argument, a directory name, and touches files in that directory and then displays a directory listing. You can run it via:
bash script.sh 'home/rrodriguez/Documents/one/'
Since home/rrodriguez/Documents/one/ is the first argument to the script, it is assigned to $1 in the script.
Notes
In shell, never put spaces on either side of the = in an assignment.
I omitted the line wc$dir/* because it wasn't clear to me what the purpose of it was.
I put double-quotes around $dir to prevent the shell from, among other things, performing word-splitting. This would matter if dir contains spaces.

In shell script, how to change current directory safely with variable?

The following shell script changes current the directory to the desktop.
v=~/Desktop/
cd $v
pwd # desktop
The following script changes the current directory to home directory instead of generating error.
cd $undefined_variable
pwd # home directory
echo $? # 0
I'm afraid that the script will remove important files if I misspelled a variable for new current directory.
Generally, how do you safely change current directory with variable in shell script?
Use:
cd ${variable:?}
if $variable is not defined or empty then bash will throw an error and exit. It's like the set -u option but not global through the file.
You can set -u to make bash exit with an error each time you expand an undefined variable.
You could use the test -d condition (checks whether the specified variable is a directory), i.e.
if [[ -d $undefined_variable ]]
then
cd $undefined_variable
echo "This will not be printed if $undefined_variable is not defined"
fi
See also here for further test options...
The Bourne Shells have a construct to substitute a value for undefined variables, ${varname-subtitution}. You can use this to have a safe fallback directory in case the variable is undefined:
cd "${undefined-/tmp/backupdir}"
If there is a variable named undefined, its value is substituted, otherwise /tmp/backupdir is substituted.
Note that I also put the variable expansion in double quotes. This is used to prevent word splitting on strings containing spaces (very common for Windows directories). This way it works even for directories with spaces.
For the gory details on all the shell substitution constructs (there are seven more for POSIX shells), read your shell manual's Parameter Substitution section.
You have to write a wrapper (this work in bash):
cd() {
if [ $# -ne 1 ] ;then
echo "cd need exactly 1 argument" >&2
return 2
fi
builtin cd "$1"
}
yes, that's shell
if you type cd without parameter it will jump to home dir.
You can can check the variable of null or empty before you cd command.
check like (cd only be called if targetDir is not empty):
test -z "$targetDir" || cd $targetDir
check like (cd only be called if targetDir really exist):
test -d "$targetDir" && cd $targetDir
Note: Thanks for -1, should read the last sentence too. So I added the real answer.

Resources