Tag Archives: IFS

Getopts inside a function is not working

By prasperl

Hi All,

I am using geopts inside a function in shell script.

But it is doesnt seem to read the input args and I always gt empty value in o/p.

my code is

Code:

This message has not been sent.
#!/bin/ksh IFS=' ' readargs(){ OPTION=$1 OPTIND=1 while getopts "i:n:o" OPTION do case $OPTION in i) input="$OPTARG" ;; n) nput="$OPTARG" ;; o) output="$OPTARG" ;; esac done echo "i is $input o is $output n is $nputn" } for i in `cat $1` do scriptname=`echo

Draft

This message has not been sent.

Actions
Click here to continue working on this message.

Thursday, July 25, 2013 11:08 AM

#!/bin/ksh
IFS='
'
readargs(){
OPTION=$1
OPTIND=1
while getopts "i:n:o" OPTION
do
case $OPTION in
i)
input="$OPTARG"
;;
n)
nput="$OPTARG"
;;
o)
output="$OPTARG"
;;

esac
done
echo "i is $input o is $output n is $nputn"
}
for i in `cat $1`
do
scriptname=`echo $i|awk '{print $1}'`
stringopts=`echo $i|awk '{$1="";print}'`
echo $scriptname
readargs $stringopts
done


Data looks like this

Code:

>cat file.txt
a.ksh -o hi -i hello -n how
c.ksh -i sam -n mi -o ki


Anything wrong with my code?

…read more

Source: FULL ARTICLE at The UNIX and Linux Forums

Comparing Data file with Crtl file

By Prashanth B

Hi,
I need to compare a file with its contents matching to that of another file(filename , received date and record count).
Lets say has File A original data

Code:

Ex -
1,abc,1234
2,bcd,4567
3,cde,8901


and File B has details of File A

Code:

Ex-
FILEA.TXT|06/17|2010|3
(filename)|(received date)|(record count)


I need to fetch the details(filename , received date and record count) File A ,and must be compared with File B and it should match.I wrote a code which covers all the requirements but it throws me an error. It throws error at line 62 stating ‘]’ missing and line 72 : argument expected. Kindly have a look at my script and let me know where I went wrong.

Original Script

Code:

echo "Initialising the run time parameter for FOLDER path..."
cd $path #path will be given here
echo "n Folder path of the unzipped files and CNTRL file: $1 "
echo "n n Reading the content from CNTRL file and asssigning the values to variables..."
while IFS='|' && read fname Process_dt rec_cnt
do
echo "n $fname $Process_dt $rec_cnt "
echo "n Checking if the File exist in the folder..."
if [ -f $fname ] ; then
echo "n $fname Exist"
echo "n n Reading linecount for the corresponding file and storing it in a variable..."

cat $fname | wc -l | read linecount
echo "n Reading Processdate for the corresponding file and storing it in a variable..."
ls -l | awk '{print $6 $7 S8}'| nawk ' { months=" JanFebMarAprMayJunJulAugSepOctNovDec";date=$2;month=index(months,substr($1,1,3))/3; year=$3; printf("%02s/%02s/%s
n",month,date,year)}'|read Proc_dt;
echo "n checking if record count and Process date of the file matches with the CNTRL file entry..."
if [ ($linecount -eq $rec_cnt) && ($Proc_dt -eq $Process_dt) ] ; then
echo "n n Record Count and Process date matches from both files"
return 0
else
if [ ($linecount -ne $rec_cnt)]
echo "n n Record Count doesnot match"
return 1
fi
else
echo "n n Process date doesnot match"
return 1
fi
fi
echo "Passing the run time parameter for CNTRL file name..."
done < POR.CRTl
echo " Filename,Record count and Process date validated against file $2"


I will be incorporating this into a cmd task where I will pass path and CRTL file name as variable.

From: http://www.unix.com/shell-programming-scripting/221355-comparing-data-file-crtl-file.html

Assign output of "ls -l" to an array

By jamarsh

I want to assign the output of a file search (ls -l) to an array, as in the following example:

Code:

-rw-rw-r-- 1 john john 121 Mar 13 22:30 ma-man~
drwxr-xr-x 8 john john 4096 Jan 7 12:06 Owner
-rw-rw-r-- 1 john john 929 Feb 7 09:40 partition_output~
drwxr-xr-x 8 john john 4096 Jan 7 12:06 test1
drwxr-xr-x 2 john john 4096 Mar 8 10:24 test3


I used this command:

Code:

array=(`ls -l)


However, instead of 5 elements in the array, I have 45. A space is being read as a field separator. I added the following:

Code:

IFS='n'


to indicate a new line, but I must be missing something.

From: http://www.unix.com/shell-programming-scripting/221183-assign-output-ls-l-array.html

Trying to create a script to run as root, permission denied

By DonnieNarco

Hello all, I am trying to create a script or a .command file that will run for me and my other techs on many, many Mac OSX computers that will add a file to the /etc/ folder called /etc/launchd.conf

Every time I try to run the script, I get “Permission Denied” when trying to put the file into the /etc/ directory.

The reason for this script is we will need to deploy this script quickly across many Macs, and it will only be run by myself or other admins. We just want to make it easier for us so we do not have to manually go to the /etc/ folder and create the launchd.conf file each time. I dont mind having to type in the root password at launch of this script, but I would prefer to not have to type in the root password each time…i would love it if this could be completely autonomous.

here are the two versions of code that I have tried so far, based on help from other Google inquiries:

Code:

#!/bin/bash

clear ; echo This script will put a system configuration file into your Mac OSX that will assist with UNIX permissions on the IFS

clear ;
echo Moving Working Directory to the System Directory
cd /etc/

echo Creating a new file with correct permissions, please have system root password ready...

sudo cat <> launchd.conf
umask 000
EOF
echo Process has completed, thank you.


and this:

Code:

#!/bin/bash

clear ; echo This script will put a system configuration file into your Mac OSX that will assist with UNIX permissions on the IFS
sleep 2
clear ;

chown root Test3.command
chmod u+s Test3.command

echo Moving Working Directory to the System Directory
cd /etc/
sleep 2
echo Creating a new file with correct permissions, please have system root password ready...
sleep 3
sudo cat < launchd.conf
umask 000
EOF
echo Process has completed, thank you.
sleep 2


Does anyone know how I can create this script for us to run?
Thank you very much.

From: http://www.unix.com/shell-programming-scripting/220907-trying-create-script-run-root-permission-denied.html

Finding row number along with length of row

By princetd001

I have a fixed length file and I want to find out row number along with row length.

I have a program that give me the line length if it satisfy the condition; but i would like to add row number as well?

How do I do that?

HTML Code:

while IFS= read -r line; do
if [ ${#line} == 4499 ]; then
echo ${line}
echo ${#line}
echo "You have access!thereis a line length of 4499"
fi
done < input.dat


Thanks ,
Prince

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Print a line

By mastansaheb

Hi,
I have a script like below

file=/etc/hosts
n=0
while IFS= read -r line
do
echo $n
n=$((n+1))
if [ $n == 3 ]
then
echo $line
fi
done < "$file"

=======================================
and i am getting output like below

0
1
2
127.0.0.1 localhost.localdomain localhost
3

My query is whenever i am running this script it should ask type the line which you want to print. So, please make me do it like this.

Regards,
Mastan

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Peculiar behavior due to IFS

By ravisingh

Code:

aa=|
echo $aa


The above echo works but the below echo fails. Why please?

Code:

IFS=:
aa=|
echo $aa
echo $IFS


The later ‘echo’ command will work if variable is put in codes.

Code:

echo "$aa"
echo "$IFS"


I summarize that when IFS is set to ‘:’ or ‘|’, echo used with variable doesn’t work unless the variable is quoted.
It took quite some time to conclude this.

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Read csv file in bash

By tdubb123

how to I use IFS to read 2 files (csv) and run the followiung script

./naviseccli -h 1.2.3.4 storagegroup -addhlu -gname $hostname -hlu $hlu_num -alu $alu_num

the csv file for $hostname is

host1
host2
.
.
.

for hlu and alu

its

alu,hlu
1,100
2,200
3,300
.
.
.

maybe I can do a while loop to read both files?

while IFS=, read $hostname
while IFS=, read alu hlu
do

./naviseccli -h 1.2.3.4 storagegroup -addhlu -gname $hostname -hlu $hlu -alu $alu
done < file1.csv
done < file2.csv

any help appreciated

thanks

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Capturing Output?

By mrm5102

Hello All,

I’m writing a Bash Script and in it I execute a piped command within a Function I wrote and I can’t seem to redirect the
stderr from the 1st pipe to stdout..?

I’m setting the output to an Array “COMMAND_OUTPUT” and splitting on newlines using this –> “( $(…) )”. By putting
the extra ( ) around the $( ), it splits the output using the IFS and sets the array elements.
Then the command after the semi-colon echos BOTH Return Codes from each command using the PIPESTATUS Array
Variable to STDOUT. which works perfectly getting the Return Codes.

Here’s the Command:


IFS="
"

COMMAND_OUTPUT=( $(cat "$SEND_FILE" 2>&1 | send_nsca $IPADDR -p 5667 -to 10 -d , -c $SEND_NSCA_CFG ; echo "EXIT_CODES=${PIPESTATUS[@]}") )


I’ve tried adding “2>&1” to each point in the Command within “$(..)”, but none seem to send the ‘cat’ command’s STDERR
to STDOUT in order to capture the error inside the Array “COMMAND_OUTPUT”.

If I set $SEND_FILE to a file that doesn’t Exist, I can see that everything gets stored in the COMMAND_OUTPUT Array
except for “cat: : No such file or directory”. Which get printed immediately when that line is executed.

Any ideas on how to redirect the stderr from the 1st pipe command to stdout? Any thoughts would be much appreciated!

Thanks in Advance,
Matt

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

How to make dynamic variable names for use in while loop?

By phpchick

i=0
while [ $i -lt $numberofproducts]
do

sizesfor0=`cat 16 | grep ‘pickSize’ -A 1 | grep ‘_sz’ | cut -d’_’ -f1`
sizesfor0=${sizesfor0//id=”lll/:}
IFS=: array0=( $sizesfor0 )
echo ${array0[1]}
i=$(( $i + 1 ))

done

So, right now I have two variables in the while statement above

sizesfor0 and array0

The above statement works, but it is hard-coded with the 0 suffix, how does one turn the above variables into sizesfor$i and array$i so that I can add 1 after each iteration to make the while loop functional?

I’ve tried doing exactly that, (changing to sizesfor$i and array$i) but there are compatibility issues.

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Thoughts on the UK Productivity Puzzle

By Karl Smith, Contributor Izabella Kaminska points to an argument that it is all about valuing capital formation: Current estimates of UK GDP are too low because the methodology undervalues private sector investments in a mature economy: Current GDP estimation methods were designed to value underdeveloped economies in which investment in tangible fixed assets is a good indicator of financial value; The private sector in mature economies like that of the UK is instead increasingly investing in other assets which are not valued by current GDP estimates; It will not be possible to improve GDP calculations to accurately reflect the value of the investments of a mature economy.   Ok but the US should have this same problem and yet However, looking through the IFS report – via Simon Wren-Lewis – it seems as if decomposition more or less answers the puzzle. The report does a decomposition and gets this The authors haltingly conclude that not much is gained from decompositional analysis The slowdown of productivity growth within industries since 2008 is important in explaining the aggregate productivity shortfall relative to the trend. The extent to which industries recover to their pre-recession trends in productivity growth will affect aggregate productivity growth going forward. Again, the trend is driven by within-industry effects and not changes in the composition of industries Right, but if you look at the results a two-part de-compossed narrative immediately comes out. First, the standard acceleration of de-industrialization, common to modern recessions: Construction and Manufacturing fell as fractions of the workforce leading to large negative “between” effects. Second, gains-from-trade which usually rescue advanced economies from aggregate productivity slowdowns failed to appear. Why? Because the good and services that the UK specializes in got whacked. Mining, which I assume is North Sea Oil, fell off a cliff. And, Finance through which London serves as banker to much of the world, also fell off a cliff. We would expect to see large “between” positives in those categories as workers shifted towards the industries in which the UK has a comparative advantage. Thus the pattern would be that all of productivity growth is being driven by increasing productivity in a few sectors which are themselves attracted ever more workers (because of the higher real wage.) That didn’t happen. Instead you got big negatives on the very sectors that one would expect to offset deindustrialization. So the total was a big negative fest. The US on the other hand has had an inverse story. Not only did manufacturing rebound, but natural resource extraction exploded. In addition the construction collapse came early. So looking at the chart below we can get the following pattern 2005: Ahh! Construction is going away 2007: Whew! We sold lots of Bulldozers to BRIC 2008: Ah! Detriot is gone. Ah!! Wall Street is gone.  Ah!! BRIC is gone On the bright side, we have a bunch of this Natural Gas stuff if anyone wants it. 2010: Yeah Detriot is coming back  Yeah Wall Street is coming back. 2011: We have more oil than God.
Source: FULL ARTICLE at Forbes Latest

Parsing cron data with awk

By Elvirnith

Heya,

I’m currently working on a script so I can see which cron jobs, if any, on a system are executing less frequently than 15 minutes (1 – 14 minutes). This is the only data I’m interested in. So far I have the following:


#!/bin/bash

IFS=$'n';for line in `ls -f /var/spool/cron/*`;
do
echo -e '5n10n0n20' | awk '{if($1 ~ "*" || ($1 ~ /^[0-9]+$/ && $1 != 0) && $1 < 15) print}' <${line};
done


That being said, I’m a bit stuck. That lists the data for minutes, but if a cron job is like so:

5 2 * * * echo “test”

It will still list that cron job, since it’s not taking into account the other columns. Is there a decent way to search out only the cron jobs that meet said criteria while excluding those which execute on the hour/day/week?

Any help is appreciated. Thanks!

Source: FULL ARTICLE at The UNIX and Linux Forums

Not able to understand IFS

By scriptor

Hi ,

i am in my initial learning phase of unix. i was going thru the function part.
below is the example which was there but i am not able to understand logic and the use of IFS(internal field separator)

Code:

lspath() {
OLDIFS="$IFS"
IFS=:
for DIR in $PATH ; do echo $DIR ; done
IFS="$OLDIFS"
}


the output is below. here i am failed to understand how the o/p is coming like below
and logic behind the IFS.

Code:

/sbin
/bin
/usr/bin
/usr/sbin
/opt/bin
/usr/ucb
/usr/ccs/bin
/usr/openwin/bin


regards,
scriptor

Source: FULL ARTICLE at The UNIX and Linux Forums

Find and replace mulitple charaters in filenames

By barrydocks

I have a virtual pdf printer set up on my server which produces files with the following prefix:

Code:

smbprn_00000044_Microsoft_Word_-_OriginalFilename.pdf


the number in the center of the file increase by one for each new file.

I want to remove all the charaters infront of
OriginalFilename.pdf using the following code:

Code:

find . -type f -name '*[:smbprn_*_Microsoft_Word_-_*.pdf"]*' | while IFS= read -r; do mv -- "$REPLY" "${REPLY//[:smbprn_*_Microsoft_Word_-_*.pdf"]}" done;


which I modified form here

If I run this directly from the command prompt I simply end up with a second
> prompt?

I think I must be pretty close, any help would be welcome

Source: FULL ARTICLE at The UNIX and Linux Forums

Parse find input into array

By jrymer

I need help parsing the output of
find into an array. I need to search 3 directories and find all files older than 31 days old. This is what I have so far.

Code:

TIME=" -maxdepth 1 -mtime +31"
DIR1="/dir1/"
DIR2="/dir2/"
DIR3="/dir3/"

FIND_DIR1=$(find ${DIR1}${TIME})
FIND_DIR3=$(find ${DIR2}${TIME})
FIND_DIR3=$(find ${DIR3}${TIME})

IFS=' ' read -a array <<< "$FIND_DIR1"
for element in "${array[@]}"
do
echo "$element"
done


When I
echo the
FIND_DIR variables, it prints out..

/dir1/file1 /dir1/file2 separated by what I’m assuming is either white space or a tab.

The issue I’m having is when I try to put the output of the
find into an array, array index 0 has both
/dir1/file1 and
/dir1/file2

I need array index 0 to be file 1 and array index 1 to be file 2.

The above code will output
/dir1/file1 for both array index 0 and array[@], it prints nothing when asked to print array index 1.

Thank you in advance.

Source: FULL ARTICLE at The UNIX and Linux Forums

Find command fails when a space is in the directory path variable

By aptaI have a script like this running under OS X 10.8. The problem arises when the find command encounters a space in the path name. I need the “dir” variable as I’ll be extending the script to more general use.

Code:
#!/bin/bash
CFS=$IFS
IFS=$(echo)

set dir = “/Users/apta/Library/Mail Downloads/2012-12-20/Testimonials.mbox/”
ls -l ${dir}
find ${dir} -name ‘*.emlx’ | xargs grep -ih “^From: ” | awk -f emlx_addresses.awk | sort -u -t “,” -k 2
The ls command works fine in the script but the find command encounters this error:

Code:
find: illegal option — n
usage: find [-H | -L | -P] [-EXdsx] [-f path] path … [expression]
find [-H | -L | -P] [-EXdsx] -f path [path …] [expression]
If I enclose the path variable with quotes
Code:
find “${dir}” -name ‘*.emlx’ | …
then this error comes up:

Code:
find: ftsopen: No such file or directory
I’m baffled; I added the IFS as suggested in another posting but it didn’t help.
Source: The UNIX and Linux Forums

Grab exactly one byte from a FIFO, at random intervals

By vomv1988I want to develop a script of the following form:

Code:
#!/bin/bash

# Function ‘listen’ opens a data stream
# which stores all incoming bytes in
# a buffer, preparing them to be
# grabbed by a following function
# which appears at random
# intervals during the execution of
# the script

listen &
INPID=${!}

# To test if the script is really capable
# of grabbing bytes randomly, the
# following code is looped over:

PROMPT=n
while test ${PROMPT} != ‘q’ ; do
printf ‘y: print next bytenn: don'”‘”‘t print next bytenq: quitn’
read -n 1 PROMPT
printf ‘n’
if test ${PROMPT} = ‘y’ ; then

# The function ‘grab1byte’ extracts
# ONE byte from the buffer being fed
# bytes by ‘listen’, and outputs it
# to stdout

INBYTE=`grab1byte`
echo The input byte is:
printf “${INBYTE}” | xxd -cols 1 | sed ‘s/^.*: //’
fi
done

kill ${INPID}
The way I’ve tried to implement this, is by using FIFOs. In one directory, I have 2 FIFOs, which I created with mkfifo; these are named ‘INPUT‘ and ‘FIFO‘. In fluxbox, I open 2 instances of xterm; in one I run the following script:

Code:
#!/bin/bash

MY_INPUT=INPUT
MY_FIFO=FIFO

# This is ‘listen’:
(
IFS=
tail -f ${MY_INPUT} | while read -N 1 CHAR ; do
printf “${CHAR}” > ${MY_FIFO}
done
) &
READPID=${!}

PROMPT=n
while test ${PROMPT} != ‘q’ ; do
printf ‘y: print next bytenn: don'”‘”‘t print next bytenq: quitn’
read -n 1 PROMPT
printf ‘n’
if test ${PROMPT} = ‘y’ ; then
# This is ‘grab1byte’:
INBYTE=`cat ${MY_FIFO}`
echo The input byte is:
printf “${INBYTE}” | xxd -cols 1 | sed ‘s/^.*: //’
fi
done

kill ${READPID}
On the other one, I run:

Code:
printf ‘Hello, world!’ > INPUT
Then, back on the first terminal, I type ‘y’ to the prompt, to test the bytegrabbing. The problem is: instead of getting only 1 byte, I sometimes get 1, 2, 3, 4, 5 bytes. A typical session looks something like:

Code:
y: print next byte
n: don’t print next byte
q: quit
y
The input byte is:
48 H
65 e
y: print next byte
n: don’t print next byte
q: quit
y
The input byte is:
6c l
6c l
6f o
2c ,
20
77 w
y: print next byte
n: don’t print next byte
q: quit
But, what I want is something like:

Code:
y: print next byte
n: don’t print next byte
q: quit
y
The input byte is:
48 H
y: print next byte
n: don’t print next byte
q: quit
y
The input byte is:
65 e
y: print next byte
n: don’t print next byte
q: quit
The mystery is: Why does FIFO spit out 2 or 4 bytes at a time, if I am only writing ONE byte at each iteration of the loop??:

Code:
IFS=
tail -n 1 -f ${MY_INPUT} | while read -N 1 CHAR ; do
printf “${CHAR}” > ${MY_FIFO}
done
The code seems to work with a ‘sleep’ delay of 0.2 right after ‘printf “${CHAR}” > ${MY_FIFO}’. But… why?

In order for this script to be perfect, I would require it to ONLY use FIFOs: No ugly and slow hard-drive file buffers, please. And also, NO ugly time delays.

Another funny thing is how, when I run in one terminal:

Code:
( IFS= ; tail -f FIFO | while read -N 1 CHAR ; do printf “${CHAR}” | xxd -cols 1 ; printf ‘..n’ ; done )
And, from another, I do

Code:
printf ‘Hello, world!’ > FIFO
I get:

Code:
0000000: 48 H
..
0000000: 65 e
..
0000000: 6c l
..
0000000: 6c l
..
0000000: 6f o
..
0000000: 2c ,
..
0000000: 20
..
0000000: 77 w
..
0000000: 6f o
..
0000000: 72 r
..
0000000: 6c l
..
0000000: 64 d
..
0000000: 21 !
..
Which goes to show that ${CHAR} never stores more than 1 byte at any given time. If it did, the output would look more like:

Code:
0000000: 48 H
0000000: 65 e
0000000: 6c l
0000000: 6c l
..
0000000: 6f o
0000000: 2c ,
0000000: 20
..
0000000: 77 w
0000000: 6f o
0000000: 72 r
0000000: 6c l
0000000: 64 d
0000000: 21 !
..
So… my question is… basically: What is the deal with this FIFO glitch? If the problem is not in the loop, then: Where is it?
Source: The UNIX and Linux Forums

Having trouble with My Bash Script, need Help debugging

By jdavis_33Hello Friends
I am having trouble with my script below. I will describe the problems below the code box. I am hoping that some of the experts here can help me.

Code:
#!/bin/bash
#=========================================================================================================
# Rsync File Restore Script [Unfinished] ********************************************* #
# This script is in /raid0/data/backup/ * * #
# * Author: Johnny J. Davis * #
# * Date Created: * #
# [ Last Modified ] * Script name: filerestore_take2.sh * #
# Date: 12/18/12 * [incomplete] * #
# Time: 9:32 AM * * #
# ********************************************* #
##########################################################################################################

#=========================================================================================================
# ****[Begin Variables]****
#=========================================================================================================
LogDns1=/raid0/data/backup/logs/dns1_file_restore.log
LogServices=/raid0/data/backup/logs/services_file_restore.log
LogInet1=/raid0/data/backup/logs/inet1_file_restore.log
LogUser=/raid0/data/backup/logs/UserLog.log
NoLog=”echo No log present for $secondhalf” # The variable $secondhalf will be assigned later
RSYNC=/usr/bin/rsync # on as a result of user input.
DATE=/bin/date
ECHO=/bin/echo
USER=root
#———————————————————————————————————
# {End Variables}
#=========================================================================================================
# ****[Begin Functions]****
#=========================================================================================================
# Function to remove previous log, if present (DNS1)
removeLogDns1(){
if [ -a $LogDns1 ]
then
rm $LogDns1
else
echo “No log present for Dns1!”
fi
}
# Function to remove previous log, if present (SERVICES)
removeLogServices(){
if [ -a $LogServices ]
then
rm $LogServices
else
echo “No log present for Services!”
fi
}
# Function to remove previous log, if present (INET1)
removeLogInet1(){
if [ -a $LogInet1 ]
then
rm $LogInet1
else
echo “No log present for Inet1!”
fi
}
#————————————————————-(Step 6)————————————
# Function that confirms the intention to restore and restores the file
# placed in the variable fileName by the fileCheck function in step 3.
restoreFile(){
echo -n “Restore $fileName? [Y/N]?> ”
read -r answer
case $answer in
Y ) echo “Restoring the file $fileName!” # Will be Adding additional commands here
;;
N ) echo “Action aborted, nothing restored!”; makeSelection
;;
* ) echo “Must answer with a Y or N!”
;;
esac
#exit 0; sh /raid0/data/backup/filerestore_take2.sh
}
#————————————————————-(Step 5a)—————————
# Function that changes the current working directory to the choice made in step 2, if infact
# it was a directory.
cdNow(){
if [ -d $choice ]
then
cd $choice; echo “Changed Directory to $PWD“; makeSelection
else # If the choice from step 2 is not a directory and
echo “This is not a directory!” # manages to make it to this step, the script will
fi # terminate with echo.
}
#————————————————————-(Step 5b)—————————
# Function checks to see if the choice from step 2, is infact a file. If so, it stores the file
# name in a variable called fileName and proceeds to call the restoreFile function in step 4.
fileCheck(){
if [ -f $choice ]
then
fileName=$choice; restoreFile
else # If the choice from step 2 is not a file
echo “This is not a file!” # and manages to make it to this step, the
fi # script will terminate with echo.
}
#———————————————————–(Step 4)————————————–
# Function that determines if the selection from step 1 is a file
# or directory and moves to next function based on the result.
checkType(){
while [ -d $choice ] # Checks the variable to see if it is a directory.
do # If so, it calls the cdNow function, in step 5a.
cdNow
break;
done

while [ -f $choice ] # Checks the variable to see if it is a file. If so,
do # it calls the fileCheck function, in step 5b.
fileCheck
break;
done
}
#————————————————————(Step 3)————————————-
# Function checks for existance of files.
anyFiles(){
ls ./* > /dev/null 2>&1
if [ “$?” = “0” ]
then
checkType
else
echo “No files exist here!”
fi
}
#————————————————————(Step 2)————————————-
# Fuction that allows selecting either a file or directory.
makeSelection(){
PS3=”Enter choice [ctrl-c quits]> ”
select choice in `for i in $(ls -p ./); do echo ${i%%.*}; done`
do echo; break; done
anyFiles
}
#———————————————————————————————————
# {End Functions}
#=========================================================================================================
# ****[Script Start]**** (Step 1)
#=========================================================================================================
#
echo
echo
echo
clear
echo “Current Working Directory: $PWD
echo
echo “Please select file or directory.”
echo
echo “[Selecton Menu]”
makeSelection
I haven’t found a way around using ‘ls’ or ‘find’ in my select statement to produce the Selection Menu. I know that they return unsafe IFS results and that it results in some files having multiple menu entries. I am still looking for a way to combat that issue. However, I would like to have someone look at it for me.

Upon execution of the script, I get some prompts duplicated after performing the task. For instance, after traversing several directories, to finally reach the file that I would like to restore. I am prompted to restore the file. I say yes to restore. I get the echo stating that the file is being restored, then immediately after, I get the same prompt. I know it’s something in the functions causing this, but I don’t know how to resolve it. Also, while entering a selection at the selection menu, I deliberately entered an invalid choice to see what would happen. It drops to /root and echos “No files exist here!” and prompts to Restore ? [Y/N]?>. I don’t know what’s causing this or how to fix it. Do you have any ideas about any of this?

Please Note, that this script is not complete. I still have much work to do.

I should also point out that I am working on a Thecus N4100Pro Nas via ssh. The box has a very limited command set, as it is running a dumbed-down version of Slackware. Some options for the commands that do exist, are non-existent on this box. For instance, ‘find’ with the -maxdepth or -mindepth options. Find is a valid command for the box, but the options do not exist.

Thanks for your help.
Source: The UNIX and Linux Forums

Shell Script to read a tab delimited file and perform simple tasks

By jsmith69321. The problem statement, all variables and given/known data:
Hello!
I need help with this problem bash shell scripting that basically just reads the data in a tab delimited file and does the following below

1. Read in the data file Survey.txt and assign the column values to variables of your choosing.
2. Calculate the total number of survey respondents.
3. Calculate the ratio of male to female respondents.
4. Calculate the average Height and Weight of the male and female respondents and compare your results.
5. Calculate the average Verbal and Math scores of the right- and left-handed respondents and compare your results.

2. Relevant commands, code, scripts, algorithms:
Attached is the Survey.txt file that this script is going to be reading.

3. The attempts at a solution (include all code and scripts):
Here is the code that I have completed so far:
Code:
#!/bin/bash
IFS=$’n’
for line in $(cat ./Survey.txt)
do
echo $line
done

4. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
Eastern Center For Arts and Technology Willow Grove PA USA Computer Network Administration Instructor Karon Crickmore

Attached Files

File Type: txt
Survey.txt (7.0 KB)

Source: The UNIX and Linux Forums

How to read records in a file and sort it?

I have a file which has number of pipe delimited records.
I am able to read the records….but I want to sort it after reading.

i=0
while IFS=”|” read -r usrId dataOwn expire email group secProf startDt endDt smhRole RoleCat DataProf SysRole MesgRole SearchProf
do

print $usrId $dataOwn $expire $email $group $secProf $startDt $endDt $smhRole $RoleCat $DataProf $SysRole $MesgRole $SearchProf

done

But I want to sort these records as per $usrId
Source: The UNIX and Linux Forums