What would be the best way to extract all the directory names from a path and compare it with directory name given as argument:
find_dir() {
path='/download/1/2/3/4/5/6'
for dir in logic ${path}
if [ dir = $1 ]; then
echo "Directory $1 found in $path"
exit(0)
else
pass
fi
echo "Directory $1 not found in $path"
}
Results:
pompt$ find_dir 4
Directory 4 found in /download/1/2/3/4/5/6
pompt$ find_dir 8
Directory 8 not found in /download/1/2/3/4/5/6
Just use regex match wrapping directory name within / (note the if [[ $dir =~ .*/$1/.* ]] ; then syntax, double brackets, space before semi-colon and =~ for regex test):
#!/bin/bash
find_dir() {
path='/download/1/2/3/4/5/6'
for dir in logic ${path}
do
if [[ "$dir" =~ .*/$1/.* ]] ; then
echo "Directory $1 found in $path"
exit 0
fi
done
echo "Directory $1 not found in $path"
}
find_dir 8
find_dir 4
result:
Directory 8 not found in /download/1/2/3/4/5/6
Directory 4 found in /download/1/2/3/4/5/6
note: I preserved the for loop but the logic argument doesn't make any sense...
You could do this:
#!/usr/bin/env bash
find_dir() {
path='/download/1/2/3/4/5/6'
lastdir=$(rev <<< "$path" | cut -f1 -d/)
n=1
while [[ $dir != $lastdir ]]; do
dir=$(cut -f$n -d/ <<< "$path")
((n++))
if [[ $dir == $1 ]]; then
echo "Directory $1 found in $path"
exit 0
fi
done
echo "Directory $1 not found in $path"
}
Related
for var in "$#"
do
if test -z $var
then
echo "missing operand"
elif [ -d $var ]
then
echo "This is a directory"
elif [ ! -f $var ]
then
echo "The file does not exist"
else
basename=$(basename $var)
dirname=$(readlink -f $var)
inodeno=$(ls -i $var| cut -d" " -f1)
read -p "remove regular file $#" input
if [ $input = "n" ]
then exit 1
fi
mv $var "$var"_"$inodeno"
echo "$basename"_"$inodeno":"$dirname" >> $HOME/.restore.info
mv "$var"_"$inodeno" $HOME/deleted
fi
done
**Hello, the above code is trying to mimic the rm command in unix. Its purpose is to remove the file .
Eg if I type in bash safe_rm file1 , it works however if type in
bash safe_rm file1 file 2 , it prompts me to remove file 1 twice and gives me a unary operater expected for line 27(if [ $input = "n" ]).
Why does it not work for two files, ideally I would like it to prompt me to remove file1 and file 2.
Thanks
read -p "remove regular file $#" input
should probably be
read -p "remove regular file $var" input
That's the basic.
And this is how I'd prefer to do it:
for T in "$#"; do
if [[ -z $T ]]; then
echo "Target is null."
elif [[ ! -e $T ]]; then
echo "Target does not exist: $T"
elif [[ -d $T ]]; then
echo "Target can't be a directory: $T"
else
BASE=${T##*/}
DIRNAME=$(exec dirname "$T") ## Could be simpler but not sure how you want to use it.
INODE_NUM=$(exec stat -c '%i' "$T")
read -p "Remove regular file $T? "
if [[ $REPLY == [yY] ]]; then
# Just copied. Not sure about its logic.
mv "$T" "${T}_${INODE_NUM}"
echo "${BASE}_${INODE_NUM}:${DIRNAME}" >> "$HOME/.restore.info"
mv "${T}_${INODE_NUM}" "$HOME/deleted"
fi
fi
done
This question already has answers here:
Determine if relative or absolute path in shell program
(4 answers)
Closed 6 years ago.
As the title says, I am trying to determine if my bash script receives a full path or a relative file to a directory as a parameter.
For some reasons the following doesn't seem to work for me:
#!/bin/bash
DIR=$1
if [ "$DIR" = /* ]
then
echo "absolute"
else
echo "relative"
fi
When I run my script with either a full path or absolute path it says:
./script.sh: line 5: [: too many arguments
relative
For some reasons I can't seem to figure this bug. Any ideas?
[ ... ] doesn't do pattern matching. /* is being expanded to the contents of /, so effectively you have
if [ "$DIR" = /bin /boot /dev /etc /home /lib /media ... /usr /var ]
or something similar. Use [[ ... ]] instead.
if [[ "$DIR" = /* ]]; then
For POSIX compliance, or if you just don't have a [[ that does pattern matching, use a case statement.
case $DIR in
/*) echo "absolute path" ;;
*) echo "something else" ;;
esac
Just test on the first character:
if [ "${DIR:0:1}" = "/" ]
One more case is paths started from ~ (tilde). ~user/some.file or ~/some.file are some kind of absolute paths.
if [[ "${dir:0:1}" == / || "${dir:0:2}" == ~[/a-z] ]]
then
echo "Absolute"
else
echo "Relative"
fi
ShellCheck automatically points out that "[ .. ] can't match globs. Use [[ .. ]] or grep."
In other words, use
if [[ "$DIR" = /* ]]
This is because [ is a regular command, so /* is expanded by the shell beforehand, turning it into
[ "$DIR" = /bin /dev /etc /home .. ]
[[ is handled specially by the shell, and doesn't have this problem.
Writing tests is fun:
#!/bin/bash
declare -a MY_ARRAY # declare an indexed array variable
MY_ARRAY[0]="/a/b"
MY_ARRAY[1]="a/b"
MY_ARRAY[2]="/a a/b"
MY_ARRAY[3]="a a/b"
MY_ARRAY[4]="/*"
# Note that
# 1) quotes around MY_PATH in the [[ ]] test are not needed
# 2) the expanded array expression "${MY_ARRAY[#]}" does need the quotes
# otherwise paths containing spaces will fall apart into separate elements.
# Nasty, nasty syntax.
echo "Test with == /* (correct, regular expression match according to the Pattern Matching section of the bash man page)"
for MY_PATH in "${MY_ARRAY[#]}"; do
# This works
if [[ $MY_PATH == /* ]]; then
echo "'$MY_PATH' is absolute"
else
echo "'$MY_PATH' is relative"
fi
done
echo "Test with == \"/*\" (wrong, becomes string comparison)"
for MY_PATH in "${MY_ARRAY[#]}"; do
# This does not work at all; comparison with the string "/*" occurs!
if [[ $MY_PATH == "/*" ]]; then
echo "'$MY_PATH' is absolute"
else
echo "'$MY_PATH' is relative"
fi
done
echo "Test with = /* (also correct, same as ==)"
for MY_PATH in "${MY_ARRAY[#]}"; do
if [[ $MY_PATH = /* ]]; then
echo "'$MY_PATH' is absolute"
else
echo "'$MY_PATH' is relative"
fi
done
echo "Test with =~ /.* (pattern matching according to the regex(7) page)"
# Again, do not quote the regex; '^/' would do too
for MY_PATH in "${MY_ARRAY[#]}"; do
if [[ $MY_PATH =~ ^/[:print:]* ]]; then
echo "'$MY_PATH' is absolute"
else
echo "'$MY_PATH' is relative"
fi
done
How does one test for the existence of files in a directory using bash?
if ... ; then
echo 'Found some!'
fi
To be clear, I don't want to test for the existence of a specific file. I would like to test if a specific directory contains any files.
I went with:
(
shopt -s dotglob nullglob
existing_files=( ./* )
if [[ ${#existing_files[#]} -gt 0 ]] ; then
some_command "${existing_files[#]}"
fi
)
Using the array avoids race conditions from reading the file list twice.
From the man page:
-f file
True if file exists and is a regular file.
So:
if [ -f someFileName ]; then echo 'Found some!'; fi
Edit: I see you already got the answer, but for completeness, you can use the info in Checking from shell script if a directory contains files - and lose the dotglob option if you want hidden files ignored.
I typically just use a cheap ls -A to see if there's a response.
Pseudo-maybe-correct-syntax-example-ahoy:
if [[ $(ls -A my_directory_path_variable ) ]] then....
edit, this will work:
myDir=(./*) if [ ${#myDir[#]} -gt 1 ]; then echo "there's something down here"; fi
You can use ls in an if statement thus:
if [[ "$(ls -a1 | egrep -v '^\.$|^\.\.$')" = "" ]] ; then echo empty ; fi
or, thanks to ikegami,
if [[ "$(ls -A)" = "" ]] ; then echo empty ; fi
or, even shorter:
if [[ -z "$(ls -A)" ]] ; then echo empty ; fi
These basically list all files in the current directory (including hidden ones) that are neither . nor ...
If that list is empty, then the directory is empty.
If you want to discount hidden files, you can simplify it to:
if [[ "$(ls)" = "" ]] ; then echo empty ; fi
A bash-only solution (no invoking external programs like ls or egrep) can be done as follows:
emp=Y; for i in *; do if [[ $i != "*" ]]; then emp=N; break; fi; done; echo $emp
It's not the prettiest code in the world, it simply sets emp to Y and then, for every real file, sets it to N and breaks from the for loop for efficiency. If there were zero files, it stays as Y.
Try this
if [ -f /tmp/foo.txt ]
then
echo the file exists
fi
ref: http://tldp.org/LDP/abs/html/fto.html
you may also want to check this out: http://tldp.org/LDP/abs/html/fto.html
How about this for whether directory is empty or not
$ find "/tmp" -type f -exec echo Found file {} \;
#!/bin/bash
if [ -e $1 ]; then
echo "File exists"
else
echo "Files does not exist"
fi
I don't have a good pure sh/bash solution, but it's easy to do in Perl:
#!/usr/bin/perl
use strict;
use warnings;
die "Usage: $0 dir\n" if scalar #ARGV != 1 or not -d $ARGV[0];
opendir my $DIR, $ARGV[0] or die "$ARGV[0]: $!\n";
my #files = readdir $DIR;
closedir $DIR;
if (scalar #files == 2) { # . and ..
exit 0;
}
else {
exit 1;
}
Call it something like emptydir and put it somewhere in your $PATH, then:
if emptydir dir ; then
echo "dir is empty"
else
echo "dir is not empty"
fi
It dies with an error message if you give it no arguments, two or more arguments, or an argument that isn't a directory; it's easy enough to change if you prefer different behavior.
# tested on Linux BASH
directory=$1
if test $(stat -c %h $directory) -gt 2;
then
echo "not empty"
else
echo "empty"
fi
For fun:
if ( shopt -s nullglob ; perl -e'exit !#ARGV' ./* ) ; then
echo 'Found some!'
fi
(Doesn't check for hidden files)
EDITED: this is more or less what I came up after #Mechanical's nice input. Any insight?
#!/bin/bash
path1="$(readlink -e "$1")"
path2="$(readlink -e "$2")"
EBADARGS=65
function checkArgsNumber()
{
if test "$#" -ne 2; then
echo "ERRORE: this script takes exactly 2 params."
exit $EBADARGS
fi
}
function checkExistence()
{
if [ ! -d $path1 ]; then
echo "ERROR: "$1" does not exist"
exit $EBADARGS
elif [ ! -d "$2" ]; then
echo "ERROR: "$2" does not exist"
exit $EBADARGS
elif [[ -L $path1 ]]; then
echo "ERROR: path1 can't be a symbolic link"
exit $EBADARGS
elif [[ -L $2 ]]; then
echo "ERROR: path2 can't be a symbolic link"
exit $EBADARGS
fi
}
function checkIfSame()
{
if [[ $path1 == $path2 ]]; then
echo "ERROR: path1 and path2 must be different directories"
exit $EBADARGS
fi
}
function checkIfSubdirectories()
{
if [[ $path1 = *$path2* ]]; then
echo "ERROR:"$1" is a $path2 subdirectory"
exit $EBADARGS
elif [[ $path2 = *$path1* ]]; then
echo "ERROR:"$2" is a $path1 subdirectory"
exit $EBADARGS
elif [[ -e "$(find $path1 -samefile $path2)" ]]; then
echo "ERROR:"$(find $path1 -samefile $path2 -print0)" and "$2" have the same inode, $path2 is a $path1 subdirectory"
exit $EBADARGS
elif [[ -e "$(find $path2 -samefile $path1)" ]]; then
echo "ERROR:"$(find $path2 -samefile $path1 -print0)" and "$2" have the same inode, $path1 is a $path2 subdirectory"
exit $EBADARGS
fi
}
checkArgsNumber "$#"
checkExistence "$#"
checkIfSame "$#"
checkIfSubdirectories "$#"
now.. this should work and I hope it is useful somehow.
Could someone explain me how the *$path2* part works? What is the name of this * * operator? Where should I go read about it?
Some problems:
Stylistic
You should probably quote the entire argument to echo, as
echo "ERROR: $1 is a subdirectory of $(readlink -e "$2")"
Without the quotes around the argument to echo, you are technically passing each word as its own parameter: echo "ERROR:somedir" "is" "a" "subdirectory".... Since echo prints its parameters in the order given, separated by spaces, the output is the same in your case. But semantically it's not what you want.
(An example where it would be different:
echo foo bar
would print foo bar.)
Error message doesn't work properly
If the arguments don't exist
$ ./check.sh nonexistent1 nonexistent2
ERROR:nonexistent1 is a subdirectory of
Obviously, this is irrelevant if you've already checked they exist.
You similarly need to check for corner cases such as where the parameters refer to the same directory:
$ mkdir a b
$ ln -s ../a b/c
$ ./check.sh a b/c
ERROR:a is a subdirectory of /dev/shm/a
Doesn't detect symbolic links
$ mkdir a b
$ ln -s ../a b/c
$ ./check.sh a b
gives no error message.
Doesn't detect mount --bind
$ mkdir a b b/c
$ sudo mount --bind a b/c
$ ./check.sh a b
gives no error message.
I'm trying to write an extremely simple script in Ubuntu which would allow me to pass it either a filename or a directory, and be able to do something specific when it's a file, and something else when it's a directory. The problem I'm having is when the directory name, or probably files too, has spaces or other escapable characters are in the name.
Here's my basic code down below, and a couple tests.
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ] ; then
echo "$PASSED is a directory";
else
if [ -f "${PASSED}" ]; then
echo "${PASSED} is a file";
else
echo "${PASSED} is not valid";
exit 1
fi
fi
And here's the output:
andy#server~ $ ./scripts/testmove.sh /home/andy/
/home/andy/ is a directory
andy#server~ $ ./scripts/testmove.sh /home/andy/blah.txt
/home/andy/blah.txt is a file
andy#server~ $ ./scripts/testmove.sh /home/andy/blah\ with\ a\ space.txt
/home/andy/blah with a space.txt is not valid
andy#server~ $ ./scripts/testmove.sh /home/andy\ with\ a\ space/
/home/andy with a space/ is not valid
All of those paths are valid, and exist.
That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[ ]]?
if [[ -d $PASSED ]]; then
echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
echo "$PASSED is a file"
else
echo "$PASSED is not valid"
exit 1
fi
Double square brackets is a bash extension to [ ]. It doesn't require variables to be quoted, not even if they contain spaces.
Also worth trying: -e to test if a path exists without testing what type of file it is.
At least write the code without the bushy tree:
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
exit 1
fi
When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:
$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$
Given that you are having problems, you should debug the script by adding:
ls -ld "${PASSED}"
This will show you what ls thinks about the names you pass the script.
Using -f and -d switches on /bin/test:
F_NAME="${1}"
if test -f "${F_NAME}"
then
echo "${F_NAME} is a file"
elif test -d "${F_NAME}"
then
echo "${F_NAME} is a directory"
else
echo "${F_NAME} is not valid"
fi
Using the "file" command may be useful for this:
#!/bin/bash
check_file(){
if [ -z "${1}" ] ;then
echo "Please input something"
return;
fi
f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
echo "DIRECTORY FOUND ($result) ";
else
echo "FILE FOUND ($result) ";
fi
}
check_file "${1}"
Output examples :
$ ./f.bash login
DIRECTORY FOUND (login: directory)
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or directory))
$ ./f.bash evil.php
FILE FOUND (evil.php: PHP script, ASCII text)
FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:
#!/bin/bash
check_file(){
local file="${1}"
[[ -s "${file}" ]] || { echo "is not valid"; return; }
[[ -d "${file}" ]] && { echo "is a directory"; return; }
[[ -f "${file}" ]] && { echo "is a file"; return; }
}
check_file ${1}
Using stat
function delete_dir () {
type="$(stat --printf=%F "$1")"
if [ $? -ne 0 ]; then
echo "$1 directory does not exist. Nothing to delete."
elif [ "$type" == "regular file" ]; then
echo "$1 is a file, not a directory."
exit 1
elif [ "$type" == "directory" ]; then
echo "Deleting $1 directory."
rm -r "$1"
fi
}
function delete_file () {
type="$(stat --printf=%F "$1")"
if [ $? -ne 0 ]; then
echo "$1 file does not exist. Nothing to delete."
elif [ "$type" == "directory" ]; then
echo "$1 is a regular file, not a directory."
exit 1
elif [ "$type" == "regular file" ]; then
echo "Deleting $1 regular file."
rm "$1"
fi
}
https://linux.die.net/man/2/stat
https://en.m.wikipedia.org/wiki/Unix_file_types
A more elegant solution
echo "Enter the file name"
read x
if [ -f $x ]
then
echo "This is a regular file"
else
echo "This is a directory"
fi
Answer based on the title:
Check if passed argument is file or directory in Bash
This works also if the provided argument has a trailing slash .e.g. dirname/
die() { echo $* 1>&2; exit 1; }
# This is to remove the the slash at the end: dirName/ -> dirName
fileOrDir=$(basename "$1")
( [ -d "$fileOrDir" ] || [ -f "$fileOrDir" ] ) && die "file or directory $fileOrDir already exists"
Testing:
mkdir mydir
touch myfile
command dirName
# file or directory mydir already exists
command dirName/
# file or directory mydir already exists
command filename
# file or directory myfile already exists
#!/bin/bash
echo "Please Enter a file name :"
read filename
if test -f $filename
then
echo "this is a file"
else
echo "this is not a file"
fi
One liner
touch bob; test -d bob && echo 'dir' || (test -f bob && echo 'file')
result is true (0)(dir) or true (0)(file) or false (1)(neither)
This should work:
#!/bin/bash
echo "Enter your Path:"
read a
if [[ -d $a ]]; then
echo "$a is a Dir"
elif [[ -f $a ]]; then
echo "$a is the File"
else
echo "Invalid path"
fi