Executing different commands with separate arguments - linux

Say that I want to make a script that extracts all tar.gz and tar.bz2 files that are listed as arguments. What I've done so far is something like:
if [[ $# =~ .*"tar.gz".* ]] || [[ $# =~ .*"tar.bz2".* ]]; then
for i in $# =~ .*"tar.gz".*; do
tar -xvzf "$i"
done
for p in $# =~ .*"tar.bz2".*; do
tar -xvjf "$p"
done
else
echo "tar.gz or tar.bz2 files required."
fi
The first line is successful at evaluating whether or not a tar.gz or tar.bz2 file exist, but my problem is the rest. The variables aren't set properly, and the script ends up trying to extract each variable listed with both extraction commands. How can I separate arguments that end with tar.gz and tar.bz2 to perform separate extractions?

You should probably iterate over arguments and test each argument, like this :
#!/bin/bash
declare -i count
for file in "$#"
do
if
[[ $file =~ .*[.]tar[.]gz$ ]]
then
tar -xvzf "$file"
elif
[[ $file =~ .*[.]tar[.]bz2$ ]]
then
tar -xvjf "$file"
else
continue
fi
count+=1
fi
((count)) || echo "tar.gz or tar.bz2 files required."
If you are OK to rely on GNU tar choosing the right decoding algorithm automatically, you can simplify this to :
#!/bin/bash
declare -i count
for file in "$#"
do
[[ $file =~ .*[.]tar[.](gz|bz2)$ ]] || continue
tar -xvf "$file"
count+=1
fi
((count)) || echo "tar.gz or tar.bz2 files required."

There isn't any built-in syntax for extracting and iterating over only matching elements of an array, as you're trying to do here.
The below is POSIX-compliant, depending on no bashisms:
count=0
for arg; do
case $arg in
*.tar.gz) tar -xvzf "$arg"; count=$(( count + 1 ));;
*.tar.bz2) tar -xjvf "$arg"; count=$(( count + 1 ));;
esac
done
if [ "$count" -eq 0 ]; then
echo "tar.gz or tar.bz2 files required" >&2
fi

A bit off-topic, when extracting with GNU tar it detects the archive type automatically from the file extension since 2007, no need to specify z|j|J.
I.e. tar xvf <filename>.

Related

Shell script to check whether the entered file name is a hidden file or not in RadHat Linux

How do i create a script to check for the file is hidden or not?
#!/bin/bash
FILE="$1"
if [ -f "$FILE" ];
then
echo "File $FILE is not hidden."
else
echo "File $FILE is hidden" >&2
fi
but it is unable to do so. Please help me.
Check if the filename begins with .:
file=$1
base=$(basename "$file")
if [[ $base == .* ]]
then echo "File $file is hidden"
else echo "File $file is not hidden"
fi
You essentially have to check if filename starts with . (period).
filename=$(basename -- "$FILE")
Then you have to use pattern matching
if [[ $filename == .* ]]
then
# do something
fi
The test command would be:
[[ "${file##*/}" == .* ]]
It's necessary to remove the path, to see if file name starts with .. Here I used prefix removal. It's the most efficient, but will choke if a file contains slashes (very unlikely, but be aware).
A full script should include a test that the given file actually exists:
#!/bin/bash
file=$1
[[ -e "$file" ]] && { echo "File does not exist: $file" >&2; exit 1; }
if [[ "${file##*/}" == .* ]]; then
echo "Hidden: $file"
else
echo "Not hidden: $file"
fi
You could also list all hidden files in a directory:
find "$dir" -name .\*
Or all not hidden files:
find "$dir" -name '[^.]*'
Depending on the task, it's probably better to use a list of hidden or not hidden files, to work on.
Also, by default, ls does not list hidden files. Unless you use -a.

How to take output from a if condition?

I don't if this method is applicable or not.
#!/bin/bash
file=$1
if [[ -x "$file" ]]
then
if [ $? = 0 ]
then
echo $file is executable
else
echo $file is not executable
fi
fi
But if i run this script with a non executable file it returns nothing
But if i run this script with a executable file it returns "name is executable"
just want to know about positional parameter working. i'm a beginner.but can i
take the output of the first if condition into $?
For such test you do not need the internal if. THis code will do the work:
#!/bin/bash
file=$1
if [[ -x "$file" ]]
then
echo $file is executable
else
echo $file is not executable
fi

Parsing ls, not recommended

I received a advice for do not parse ls, like describes in this website: Don't parse ls.
I was looking for DAILY files in my directory so that's what I did then:
for f in *.DA*; do
[[ -e $f ]] || continue
for file in $f; do
echo "The file that you are working on: "$file
archiveContent=$( sed -n -e 1p $file )
echo $archiveContent
done
done
Ok, that's works well, I've two files A.DAILY and B.DAILY, with the both archives I can get what is inside it, but when I changed a little bit the loop, it doesn't iterated with all files with .DAILY extension in my directory.
for f in *.DA*; do
[[ -e $f ]] || continue
for file in $f; do
echo "The file that you are working on: "$file
archiveContent=$( sed -n -e 1p $file )
echo $archiveContent
COMPRESS $archiveContent;
done
done
when I called a function inside the loop, the loop just does for the first file, but not to the second.
Since the outer loop sets f to each file in turn, your inner loop doesn't seem to serve any purpose.
for f in *.DA*; do
[[ -e $f ]] || continue
echo "The file that you are working on: $f"
archiveContent=$( sed -n -e 1p "$f" )
echo "$archiveContent"
COMPRESS "$archiveContent"
done

restore in linux bash scripting

Help needed. This is script that I use to perform a restoration of a file from dustbin directory to its original location. It was located before in root. Then using other script it was "deleted" and stored in dustbin directory, and its former location was documented in storage file using this:
case $ans in
y) echo "`readlink -f $1`" >>home/storage & mv $1 /home/dustbin ;;
n) echo "File not deleted." ;;
*) echo "Please input answer." ;;
esac
So when using the script below I should restore the deleted file, but the following error comes up.
#!/bin/sh
if [ "$1" == "-n" ] ; then
cd ~/home/dustbin
restore="$(grep "$2" "$home/storage")"
filename="$(basename "$restore")"
echo "Where to save?"
read location
location1="$(readlink -f "$location")"
mv -i $filename "$location1"/$filename
else
cd ~/home
storage=$home/storage
restore="$(grep "$1" "$storage")"
filename="$(basename "$restore")"
mv -i $filename $restore
fi
error given - mv: missing file operand
EDIT:
so okay, I changed my script to something like this.
#!/bin/sh
if [ $1 ] ; then
cd ~/home
storage=~/home/storage
restore="$(grep "$1" "$storage")"
filename="$(basename "$restore")"
mv -i "$filename" "$restore"
fi
and still I get error:
mv: cannot stat `filename': No such file or directory
You might want to do some basic error handling to see if $filename exists before you use it as part of mv:
For example, before:
mv -i $filename "$location1"/$filename
You should probably do a:
if [[ -e "$filename" ]]; then
# do some error handling if you haven't found a filename
fi
The -e option checks whether the next argument to [[ refers to a filename that exists. It evaluates to true if so, false otherwise. (Alternatively, use -f to check if it's a regular file)
Or at least:
if [[ -z "$filename" ]]; then
# do some error handling if you haven't found a filename
fi
The -z option checks whether the next argument to [[ is the empty string. It evaluates to true if so, false otherwise.
Similar comment about: mv -i $filename $restore in your else clause.
Here's a list of test options.
You do
cd ~/home
and
mv -i "$filename" "$restore"
while the file is located in the dustbin directory, therefore, it is not found.
Do either
cd ~/home/dustbin
or
mv -i "dustbin/$filename" "$restore"
or just do
mv -i "~/home/dustbin/$filename" "$restore"
and drop the cd.

Expand a possible relative path in bash

As arguments to my script there are some file paths. Those can, of course, be relative (or contain ~). But for the functions I've written I need paths that are absolute, but do not have their symlinks resolved.
Is there any function for this?
MY_PATH=$(readlink -f $YOUR_ARG) will resolve relative paths like "./" and "../"
Consider this as well (source):
#!/bin/bash
dir_resolve()
{
cd "$1" 2>/dev/null || return $? # cd to desired directory; if fail, quell any error messages but return exit status
echo "`pwd -P`" # output full, link-resolved path
}
# sample usage
if abs_path="`dir_resolve \"$1\"`"
then
echo "$1 resolves to $abs_path"
echo pwd: `pwd` # function forks subshell, so working directory outside function is not affected
else
echo "Could not reach $1"
fi
http://www.linuxquestions.org/questions/programming-9/bash-script-return-full-path-and-filename-680368/page3.html has the following
function abspath {
if [[ -d "$1" ]]
then
pushd "$1" >/dev/null
pwd
popd >/dev/null
elif [[ -e "$1" ]]
then
pushd "$(dirname "$1")" >/dev/null
echo "$(pwd)/$(basename "$1")"
popd >/dev/null
else
echo "$1" does not exist! >&2
return 127
fi
}
which uses pushd/popd to get into a state where pwd is useful.
Simple one-liner:
function abs_path {
(cd "$(dirname '$1')" &>/dev/null && printf "%s/%s" "$PWD" "${1##*/}")
}
Usage:
function do_something {
local file=$(abs_path $1)
printf "Absolute path to %s: %s\n" "$1" "$file"
}
do_something $HOME/path/to/some\ where
I am still trying to figure out how I can get it to be completely oblivious to whether the path exists or not (so it can be used when creating files as well).
This does the trick for me on OS X: $(cd SOME_DIRECTORY 2> /dev/null && pwd -P)
It should work anywhere. The other solutions seemed too complicated.
If your OS supports it, use:
realpath -s "./some/dir"
And using it in a variable:
some_path="$(realpath -s "./some/dir")"
Which will expand your path. Tested on Ubuntu and CentOS, might not be available on yours. Some recommend readlink, but documentation for readlink says:
Note realpath(1) is the preferred command to use for canonicalization functionality.
In case people wonder why I quote my variables, it's to preserve spaces in paths. Like doing realpath some path will give you two different path results. But realpath "some path" will return one. Quoted parameters ftw :)
Thanks to NyanPasu64 for the heads up. You'll want to add -s if you don't want it to follow the symlinks.
Use readlink -f <relative-path>, e.g.
export FULLPATH=`readlink -f ./`
Maybe this is more readable and does not use a subshell and does not change the current dir:
dir_resolve() {
local dir=`dirname "$1"`
local file=`basename "$1"`
pushd "$dir" &>/dev/null || return $? # On error, return error code
echo "`pwd -P`/$file" # output full, link-resolved path with filename
popd &> /dev/null
}
on OS X you can use
stat -f "%N" YOUR_PATH
on linux you might have realpath executable. if not, the following might work (not only for links):
readlink -c YOUR_PATH
There's another method. You can use python embedding in bash script to resolve a relative path.
abs_path=$(python3 - <<END
from pathlib import Path
path = str(Path("$1").expanduser().resolve())
print(path)
END
)
self edit, I just noticed the OP said he's not looking for symlinks resolved:
"But for the functions I've written I need paths that are absolute, but do not have their symlinks resolved."
So guess this isn't so apropos to his question after all. :)
Since I've run into this many times over the years, and this time around I needed a pure bash portable version that I could use on OSX and linux, I went ahead and wrote one:
The living version lives here:
https://github.com/keen99/shell-functions/tree/master/resolve_path
but for the sake of SO, here's the current version (I feel it's well tested..but I'm open to feedback!)
Might not be difficult to make it work for plain bourne shell (sh), but I didn't try...I like $FUNCNAME too much. :)
#!/bin/bash
resolve_path() {
#I'm bash only, please!
# usage: resolve_path <a file or directory>
# follows symlinks and relative paths, returns a full real path
#
local owd="$PWD"
#echo "$FUNCNAME for $1" >&2
local opath="$1"
local npath=""
local obase=$(basename "$opath")
local odir=$(dirname "$opath")
if [[ -L "$opath" ]]
then
#it's a link.
#file or directory, we want to cd into it's dir
cd $odir
#then extract where the link points.
npath=$(readlink "$obase")
#have to -L BEFORE we -f, because -f includes -L :(
if [[ -L $npath ]]
then
#the link points to another symlink, so go follow that.
resolve_path "$npath"
#and finish out early, we're done.
return $?
#done
elif [[ -f $npath ]]
#the link points to a file.
then
#get the dir for the new file
nbase=$(basename $npath)
npath=$(dirname $npath)
cd "$npath"
ndir=$(pwd -P)
retval=0
#done
elif [[ -d $npath ]]
then
#the link points to a directory.
cd "$npath"
ndir=$(pwd -P)
retval=0
#done
else
echo "$FUNCNAME: ERROR: unknown condition inside link!!" >&2
echo "opath [[ $opath ]]" >&2
echo "npath [[ $npath ]]" >&2
return 1
fi
else
if ! [[ -e "$opath" ]]
then
echo "$FUNCNAME: $opath: No such file or directory" >&2
return 1
#and break early
elif [[ -d "$opath" ]]
then
cd "$opath"
ndir=$(pwd -P)
retval=0
#done
elif [[ -f "$opath" ]]
then
cd $odir
ndir=$(pwd -P)
nbase=$(basename "$opath")
retval=0
#done
else
echo "$FUNCNAME: ERROR: unknown condition outside link!!" >&2
echo "opath [[ $opath ]]" >&2
return 1
fi
fi
#now assemble our output
echo -n "$ndir"
if [[ "x${nbase:=}" != "x" ]]
then
echo "/$nbase"
else
echo
fi
#now return to where we were
cd "$owd"
return $retval
}
here's a classic example, thanks to brew:
%% ls -l `which mvn`
lrwxr-xr-x 1 draistrick 502 29 Dec 17 10:50 /usr/local/bin/mvn# -> ../Cellar/maven/3.2.3/bin/mvn
use this function and it will return the -real- path:
%% cat test.sh
#!/bin/bash
. resolve_path.inc
echo
echo "relative symlinked path:"
which mvn
echo
echo "and the real path:"
resolve_path `which mvn`
%% test.sh
relative symlinked path:
/usr/local/bin/mvn
and the real path:
/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn
Do you have to use bash exclusively? I needed to do this and got fed up with differences between Linux and OS X. So I used PHP for a quick and dirty solution.
#!/usr/bin/php <-- or wherever
<?php
{
if($argc!=2)
exit();
$fname=$argv[1];
if(!file_exists($fname))
exit();
echo realpath($fname)."\n";
}
?>
I know it's not a very elegant solution but it does work.

Resources