Bash script - Nested If Statement for If File Doesn't Exist - bash

I'm trying to compile a script that will read user input, and check if the file after the y/n statement. Then it will make files executable. I think the problem with my script is conditional ordering but check it out yourself:
target=/home/user/bin/
cd $target
read -p "This will make the command executable. Are you sure? (y/n)" CONT
if [ "$CONT" == "y" ];
then
chmod +x $1
echo "File $1 is now executable."
else
if [ "$(ls -A /home/user/bin/)" ];
then
echo "File not found."
else
echo "Terminating..."
fi
fi
As I said, I need the script to scan for the file after the y/n statement is printed. The script works fine how it is but still gives the "file is now executable" even if the argument file doesn't exist (but just gives the standard system "cannot find file" message after the echo'd text).

Your script is mostly correct, you just need to check if the file exists first. Also, it's not the best practice to use cd in shell scripts and not needed here.
So re-writing it
#!/bin/bash
target="/home/user/bin/$1"
if [[ ! -f $target ]]; then
echo "File not found."
else
read -p "This will make the command executable. Are you sure? (y/n) " CONT
if [[ $CONT == "y" ]]; then
chmod +x "$target"
echo "File $1 is now executable."
else
echo "Terminating..."
fi
fi

To get an understanding:
Your script will take one argument (a name of a file).
You ask if you want to make that file executable.
If the answer is 'yes', you make the file executable.
Otherwise, you don't.
You want to verify that the file exists too?
I'm trying to understand your logic. What does this:
if [ "$(ls -A /home/user/bin/)" ];
suppose to do. The [ ... ] syntax is a test. And, it has to be one of the valid tests you see here. For example, There's a test:
-e file: True if file exists.
That mean, I can see if your file is under /home/user/bin:
target="/home/user/bin"
if [ -e "$target/$file" ] # The "-e" test for existence
then
echo "Hey! $file exists in the $target directory. I can make it executable."
else
echo "Sorry, $file is not in the $target directory. Can't touch it."
fi
Your $(ls -A /home/user/bin/) will produce a file listing. It's not a valid test like -e unless it just so happens that the first file in your listing is something like -e or -d.
Try to clarify what you want to do. I think this is something more along the lines you want:
#! /bin/bash
target="/home/user/bin"
if [ -z "$1" ] # Did the user give you a parameter
then
echo "No file name given"
exit 2
fi
# File given, see if it exists in $target directory
if [ ! -e "$target/$1" ]
then
echo "File '$target/$1' does not exist."
exit 2
fi
# File was given and exists in the $target directory
read -p"Do you want $target/$1 to be executable? (y/n)" continue
if [ "y" = "$continue" ]
then
chmod +x "$target/$1"
fi
Note how I'm using the testing, and if the testing fails, I simply exit the program. This way, I don't have to keep embedding if/then statements in if/then statements.

Related

Why does $# always return 0?

I'm trying to write a script that will only accept exactly one argument. I'm still learning so I don't understand what's wrong with my code. I don't understand why, even though I change the number of inputs the code just exits. (Note: I'm going to use $dir for later if then statements but I haven't included it.)
#!/bin/bash
echo -n "Specify the name of the directory"
read dir
if [ $# -ne 1 ]; then
echo "Script requires one and only one argument"
exit
fi
You can use https://www.shellcheck.net/ to double check your syntax.
$# tells you how many arguments the script was called with.
Here you have two options.
Option 1: Use arguments
#!/bin/bash
if [[ $# -ne 1 ]]
then
echo "Script requires one and only one argument"
exit 1
else
echo "ok, arg1 is $1"
fi
To call the script do: ./script.bash argument
Use [[ ]] for testing conditions (http://mywiki.wooledge.org/BashFAQ/031)
exit 1: by default when a script exists with a 0 status code, it means it worked ok. Here since it is an error, specify a non-zero value.
Option 2: Do not use arguments, ask the user for a value.
Note: this version does not use arguments at all.
#!/bin/bash
read -r -p "Specify the name of the directory: " dir
if [[ ! -d "$dir" ]]
then
echo "Error, directory $dir does not exist."
exit 1
else
echo "ok, directory $dir exists."
fi
To call the script do: ./script.bash without any arguments.
You should research bash tutorials to learn how to use arguments.

Bash script not recognizing file

I am attempting to write a bash script. In a test, I wrote a script to check for the existence of test.txt. However, no matter how many times I try to change the formatting, the code still does not recognize the file.
while [ "$INPUT" != "quit" ]; do
read INPUT
COMMANDFILE=test.txt
if [ -f $COMMANDFILE ]; then
echo "Found file!"
fi
done
I am 100% positive text.txt exists and is in the same folder as my script.
in this case I would add some debug lines to my script to make sure my thinking is correct. For instance:
while [ "$INPUT" != "quit" ]; do
read INPUT
COMMANDFILE=test.txt
echo "debug: now I'm in $( pwd ) directory. dir listing:"
ls -la
if [ -f $COMMANDFILE ]; then
echo "Found file!"
fi
done
also, please note that linux filenames are case sensitive (meaning you can have test.txt and TeSt.txt in the same directory). So, for instance if you have the file named TEST.TXT, [ -f test.txt ] will evaluate to false (unless test.txt exists as well)

How do I combine an "if" and a "while loop" statement together?

New to shell scripting and I want to test to see if the variables I created are valid directories and if not send the user into a while loop to enter the directory and only allow exit when a valid directory is entered.
So far this is what my script looks like:
~/bin/bash
source_dir="$1"
dest_dir="$2"
mkdir /#HOME/$source_dir
mkdir /#HOME$dest_dir
if [ -d "$source_dir" ]
then
echo "$source_dir is a valid directory"
fi
while [[ ! -d "$source_dir" ]]
do
echo "Please enter a valid directory"
read source_dir
done
Is there any way to combine these into a single statement?
The while code will never execute if the directory is valid. Therefore just move the echo "$source_dir is a valid directory" after the loop:
#!/bin/bash
source_dir="$1"
dest_dir="$2"
mkdir "$HOME/$source_dir"
mkdir "$HOME/$dest_dir"
until [[ -d "$source_dir" ]]
do
read -p "Please enter a valid directory" source_dir
done
echo "$source_dir is a valid directory"
Notes:
a few code typos were fixed, e.g. /#HOME$dest_dir should be "$HOME/$dest_dir".
any while ! can be shortened to until.
The above code lacks a few things:
It tries create a new dir, then if that fails, has the user enter an already existing directory. It might be better to let the user create a new directory, but only if it doesn't already exist.
It would be better to check if $dest_dir exists.
Here's a more thorough approach using a shell function:
#!/bin/bash
untilmkdir ()
{
d="$1";
until mkdir "$d" ; do
read -p "Please enter a valid directory: " d
[ -d "$d" ] && break
done;
echo "$d is a valid directory" 1>&2
echo "$d"
}
source_dir=$(untilmkdir "$HOME/$1")
dest_dir=$(untilmkdir "$HOME/$2")
Notes:
The prompts in untilmkdir are printed to stderr.
The name of whatever directory untilmkdir creates is printed to stdout.
Having untilmkdir print to both stderr and stdout allows storing the successfully created name to a variable.

Unix while loop to test command line argument if it is a directory

Trying to make a script that will take a command line argument as a pathname and then test if it is a working directory. Then I wish to run commands (tests) on the directory such as how many files in what sub directories etc.
I am unable to think of a logic to test this with. How would you determine if the argument is a directory?
This is what I have tried
if [ -d "$1" ]
then
echo "It works"
fi
I dont get "It works" when I try this. So I switched it to -a for a file because it is easier to test. And again, I do not get the echo output.
Use the -d option to the test command.
if [ -d "$1" ]
then ...
fi
The title mentions a while loop, but none of the previous commentary seems to mention that. You might try a simple script like:
#!/bin/sh
for arg; do
if test -d "$arg";
echo "$arg is a directory"
else
echo "$arg is not a directory"
fi
done
For variety, you could rewrite that as:
#!/bin/sh
for arg; do
not=$(test -d "$arg" || echo "NOT ")
echo "$arg is ${not}a directory"
done

Bash: If statement nested in for loop

I am writing a simple script to check if an entered directory path exists. This is what I have
echo "Please specify complete directory path"
read file_path
for file in $file_path; do
if [[ -d "$file" ]]; then
echo "$file is a directory"
break
else
echo "$file is not a directory, please try again."
fi
done
What I need is if it is not a directory to go back and ask for the file path again.
Thanks.
How about this?
echo "Please specify complete directory path"
while read file; do
if [[ -d "$file" ]]; then
echo "$file is a directory"
break
fi
echo "$file is not a directory, please try again."
done
No need to split the path into its parts, testing the entire path with -d will tell you whether or not it is a directory. You need to put the entire test into a while loop until the user gets it right:
#/bin/sh
set -e
file_path=''
while [ ! -d "$file_path" ]
do
echo "Please specify complete directory path"
read file_path
if [ ! -d "$file_path" ]
then
echo "$file_path is not a directory, please try again."
fi
done
I can use it like this
$ sh /tmp/test.sh
Please specify complete directory path
foobar
foobar is not a directory, please try again.
Please specify complete directory path
/var/www

Resources