Bash script - File directory does not exist - bash

I'm creating a very simple bash script that will check to see if the directory exists, and if it doesn't, create one.
However, no matter what directory I put in it doesn't find it!
Please tell me what I'm doing wrong.
Here is my script.
#!/bin/bash
$1="/media/student/System"
if [ ! -d $1 ]
then
mkdir $1
fi
Here is the command line error:
./test1.sh: line 2: =/media/student/System: No such file or directory

Try this
#!/bin/bash
directory="/media/student/System"
if [ ! -d "${directory}" ]
then
mkdir "${directory}"
fi
or even shorter with the parent argument of mkdir (manpage of mkdir)
#!/bin/bash
directory="/media/student/System"
mkdir -p "${directory}"

In bash you are not allow to start a variable with a number or a symbol except for an underscore _. In your code you used $1 , what you did there was trying to assign "/media/student/System" to $1, i think maybe you misunderstood how arguments in bash work. I think this is what you want
#!/bin/bash
directory="$1" # you have to quote to avoid white space splitting
if [[ ! -d "${directory}" ]];then
mkdir "$directory"
fi
run the script like this
$ chmod +x create_dir.sh
$ ./create_dir.sh "/media/student/System"
What the piece of code does is to check if the "/media/student/System" is a directory, if it is not a directory it creates the directory

Related

How to write a while loop where I'm using -d option in test condition?

How do I test a directory in a while loop where if the directory doesn't exist, then it does the following blank things. I'm trying to prompt the user for input when the directory doesn't exist so the user can retry. Once they get it right, then the script exits.
My script has an infinite loop and I don't know how to fix it. Here is what my bash script looks like:
#!/bin/bash
source_dir=$1
dest_dir=$2
while [[ ! -d "$source_dir" ]]
do
echo "This is not a directory. Enter the source directory: "
read "$source_dir"
done
while [[ ! -d "$dest_dir" ]]
do
echo "This is not a directory. enter the destination directory: "
read "$dest_dir"
done
Certainly,
read "$source_dir"
does not make sense. To understand this, assume that your script is called with the parameter FOO. Hence, you first set source_dir to FOO, and the test [[ -d $source_dir ]] will do a [[ -d FOO ]] and the directory FOO does not exist. Therefore you perform your read command, which will parameter-expand into read FOO. This means to read one line from STDIN and store it into the variable FOO.
If you want to change the value of the variable source_dir, you have to do a
read source_dir

How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')"

mkdir $(date '+%d-%b-%Y')
then cd to the dynamically created directory
How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')" and do the operations by moving into the created directory in bash script
Simple way would be, you store the directory name in a variable
dirname=$(date '+%d-%b-%Y')
if [ -n "$dirname" ]; then
mkdir "$dirname"
if [ -d "$dirname" ]; then
cd "$dirname"
fi
fi
Added some error handling and also if your file is written in Windows and being run in an unix environment or vice-versa, I would recommend using dos2unix which will handle the new line character conversions (this is for the ? characters OP is seeing in ls).
Can you show me your case?
In most cases, you should not cd in to the directory. Use absolute path instead:
Good practice:
mkdir /tmp/mydir/
cp -R /usr/local/example/ /tmp/mydir/
sed 's/foo/bar/g' /tmp/mydir/afile
Bad practice:
mkdir /tmp/mydir/
cd /tmp/mydir/
cp -R /usr/local/example/ .
sed 's/foor/bar/g' afile
P.S.
Subj:
$ mkdir $(date '+%d-%b-%Y')
$ cd $(date '+%d-%b-%Y')
$ pwd
/Users/user/18-Feb-2019
In Bash, $_ expands to the last argument to the previous command. So you could do:
mkdir $(date '+%d-%b-%Y')
cd $_
In a real Bash program you would want to quote the expansions (use Shellcheck on your code to check for missing quotes), and check for errors on both mkdir and cd.

script shell mv with wildcard does not work

I am trying to copy all files in a directory starting with a certain prefix using wildcard. Here is my script
#!/bin/bash
path="/home/scoubidou/recovered/"
prefix="f"
for i in "$#"
do
if [ ! -d "$path$prefix$i" ]; then
mkdir $path$prefix$i
fi
echo $path$prefix$i* $path$prefix$i
mv $path$prefix$i* $path$prefix$i
done
However, this is not working. The wildcard seems not to be working and the expression is taken with a string. Note that the command works just fine in the terminal.
try this
`mv $path$prefix$i* $path$prefix$i`

How to change current working directory inside command_not_found_handle

I'm trying to write a not found handle in Bash that does the following:
If $1 exists and it's a directory, cd into it.
If $1 exists inside a user defined directory $DEV_DIR, `cd into it.
If the previous conditions don't apply, fail.
Right now I have something like this:
export DEV_DIR=/Users/federico/programacion/
function command_not_found_handle () {
if [ -d $1 ]; then # the dir exists in '.'
cd $1
else
to=$DEV_DIR$1
if [ -d $to ]; then
cd $to
echo `pwd`
else
echo "${1}: command not found"
fi
fi
}
And although it seems to be working (the echo pwd command prints the expected dir), the directory in the actual shell does not change.
I was under the impression that since this is a function inside my .bashrc the shell wouldn't fork and I could do the cd but apparently that's not working. Any tips on how to solve this would be appreciated.
I think what's going on is that the shell fork()s after setting up any redirections but before looking for commands, so command_not_found_handle can't affect the interactive shell process.
What you seem to want to do may partly possible using the autocd feature:
shopt -s autocd
From man bash:
autocd - If set, a command name that is the name of a directory
is executed as if it were the argument to the cd com‐
mand. This option is only used by interactive shells.
Otherwise, just create a function that you invoke by name that performs the actions you are trying to use command_not_found_handle for.
It won't change directies if you run this program as a script in your main shell because it creates a sub-shell when it executes. If you source the script in your current shell then it will have the desired effect.
~/wbailey> source command_not_found.sh
That said, I think the following would achieve the same result:
wesbailey#feynman:~/code_katas> cd xxx 2> /dev/null || cd ..; pwd
/Users/wesbailey
just replace the ".." with your env var defined directory and create an alias in your .bashrc file.
I've had the very same wish and the solution that I've been using for a while was opening a new tab in gnome terminal by issuing the command gnome-terminal --tab --working-directory="$FOLDER" from inside the command_not_found handle.
But today I've come up with a solution which is not tied to a specific terminal application, but has exactly the intended behaviour.
The solution uses the PROMPT_COMMAND, which is run before each prompt. The PROMPT_COMMAND is bound to a function responsible for checking for a file related to current shell, and cd'ing into the directory specified in that file.
Then, the command_not_found_handle fills in the file when a change in directory is desired. My original command_not_found_handle also checkout a git branch if the current directory is a git repository and the name matches an existing branch. But to keep focus on answering the current question, I've stripped that part of code.
The command_not_found_handle uses find for searching for the directory matching the given name and goes only 2 levels deep in the directory tree, starting from a configured list.
The code to be added to bash_rc follows:
PROMPT_COMMAND=current_shell_cd
CD_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/bash-cd/$$.cd"
current_shell_cd() {
if [ -r "$CD_FILE" ]; then
local CD_TARGET="$( cat "$CD_FILE" )"
[ ! -z "$CD_TARGET" ] && cd "$CD_TARGET" 2>/dev/null
rm "$CD_FILE"
fi
}
command_not_found_handle () {
local COMMAND="$1";
# List folders which are going to be checked
local BASE_FOLDER_LIST=(
"$HOME/Desenvolvimento"
"/var/www/html"
"$HOME/.local/opt/"
)
local FOLDER=$(
find "${BASE_FOLDER_LIST[#]}" \
-maxdepth 2 -type d \
-iname "$COMMAND" -print -quit )
if [ ! -z "$FOLDER" -a -d "$FOLDER" ]
then
mkdir -p "$( dirname "$CD_FILE" )"
echo "$FOLDER" > "$CD_FILE"
else
printf "%s: command not found\n" "$1" 1>&2
return 127
fi
}

Quick bash script to run a script in a specified folder?

I am attempting to write a bash script that changes directory and then runs an existing script in the new working directory.
This is what I have so far:
#!/bin/bash
cd /path/to/a/folder
./scriptname
scriptname is an executable file that exists in /path/to/a/folder - and (needless to say), I do have permission to run that script.
However, when I run this mind numbingly simple script (above), I get the response:
scriptname: No such file or directory
What am I missing?! the commands work as expected when entered at the CLI, so I am at a loss to explain the error message. How do I fix this?
Looking at your script makes me think that the script you want to launch a script which is locate in the initial directory. Since you change you directory before executing it won't work.
I suggest the following modified script:
#!/bin/bash
SCRIPT_DIR=$PWD
cd /path/to/a/folder
$SCRIPT_DIR/scriptname
cd /path/to/a/folder
pwd
ls
./scriptname
which'll show you what it thinks it's doing.
I usually have something like this in my useful script directory:
#!/bin/bash
# Provide usage information if not arguments were supplied
if [[ "$#" -le 0 ]]; then
echo "Usage: $0 <executable> [<argument>...]" >&2
exit 1
fi
# Get the executable by removing the last slash and anything before it
X="${1##*/}"
# Get the directory by removing the executable name
D="${1%$X}"
# Check if the directory exists
if [[ -d "$D" ]]; then
# If it does, cd into it
cd "$D"
else
if [[ "$D" ]]; then
# Complain if a directory was specified, but does not exist
echo "Directory '$D' does not exist" >&2
exit 1
fi
fi
# Check if the executable is, well, executable
if [[ -x "$X" ]]; then
# Run the executable in its directory with the supplied arguments
exec ./"$X" "${#:2}"
else
# Complain if the executable is not a valid
echo "Executable '$X' does not exist in '$D'" >&2
exit 1
fi
Usage:
$ cdexec
Usage: /home/archon/bin/cdexec <executable> [<argument>...]
$ cdexec /bin/ls ls
ls
$ cdexec /bin/xxx/ls ls
Directory '/bin/xxx/' does not exist
$ cdexec /ls ls
Executable 'ls' does not exist in '/'
One source of such error messages under those conditions is a broken symlink.
However, you say the script works when run from the command line. I would also check to see whether the directory is a symlink that's doing something other than what you expect.
Does it work if you call it in your script with the full path instead of using cd?
#!/bin/bash
/path/to/a/folder/scriptname
What about when called that way from the command line?

Resources