Run commands from a text file through a bash script - linux

I am attempting to write a script that will read through a text file, and then execute every line that begins with the word "run" or "chk" as a command. This is what I have thus far:
#!/bin/bash
counter=1
for i in $#
do
while read -r line
do
if [[ ${line:0:4} == "run " ]]
then
echo "Now running line $counter"
${line:4:${#line}}
elif [[ ${line:0:4} == "chk " ]]
then
echo "Now checking line $counter"
${line:4:${#line}}
elif [[ ${line:0:2} == "# " ]]
then
echo "Line $counter is a comment"
else
echo "Line $counter: '$line' is an invalid line"
fi
counter=$((counter+1))
done<$i
done
However, when I feed it a text file with, for example the commands
run echo > temp.txt
It does not actually create a file called temp.txt, it just echoes "> temp.txt" back to the stdout. It also does a similar thing when I attempt to do something like
run program arguments > filename.txt
It does not put the output of the program in a file as I want, but it rather tries to treat the '>' as a file name.
I know this is a super specific and probably obvious thing, but I am very new to bash and all shell scripting.
Thanks

You need to use eval to do all the normal shell parsing of the variable:
eval "${line:4}"
You also don't need :${#line}. If you leave out the length, it defaults to the rest of the string.

Related

shell prompt not showing up after running a script

as per http://linuxcommand.org/lc3_wss0150.php i am trying to run this script
#!/bin/bash
# Program to print a text file with headers and footers
TEMP_FILE=./printfile.txt
pr $1 > $TEMP_FILE
echo -n "Print file? [y/n]: "
read
if [ "$REPLY" = "y" ]; then
less $TEMP_FILE
fi
but when i run it via
./print_demo.bash
which is what it is saved as in my bin directory, it does not echo "Print file? [y/n]:" and also does not return the shell prompt. i have to ctrl^c to get it back.
That script is expecting input.
pr "$1" > $TEMP_FILE
The $1 represents the first argument from the command line
./print_demo.bash <printable_filename_here.txt>

exit from STDIN from bash script when the user want to close it

I'm automating the file creation from a bash script. I generated a file rc_notes.txt which has commit messages from two tags and want to re-write that in a new file as rc_device.txt.
I want the user to write the customer release notes and exit from the BASH STDIN that I prompt in the terminal.
The problem in my script is I'm not able to trap the close of file.
Wondering how to do. I don't want to trap the close signal. I want to enter magic string example: Done or some string that triggers the closure of STDIN, that exit from the script gracefully.
My script:
#/bin/bash
set -e
echo "Creating the release candiate text"
rc_file=rc_updater_notes.txt
echo "=========Reading the released commit message file=========="
cat $rc_file
echo "=========End of the commit message file=========="
echo "Now write the release notes"
#exec < /dev/tty
while read line
do
echo "$line"
done < "${1:-/dev/stdin}" > rc_file.txt
It does create the file but I need to exit manually by entering ctrl+D or ctrl+z. I don't want to do that. Any suggestions?
To break the loop when "Done" is entered
while read line
do
if [[ $line = Done ]]; then
break;
fi
echo "$line"
done < "${1:-/dev/stdin}" > rc_file.txt
or
while read line && [[ $line != Done ]]
do
echo "$line"
done < "${1:-/dev/stdin}" > rc_file.txt

How can I keep file name to variable from this code

readLBL.sh
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
When I run this shell script in Terminal and I have to insert file name for run it
Example :
./readLBL.sh science.txt
output :
58050364;Tom Jones
58050365;Marry Jane
how can i keep "science.txt" into some variable like a = "science.txt"
Use $1 as this is the argument you are already using to read the file in the first instance.
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "Text read from file $1: $line"
done < "$1"
Running this gives the following:
$ ./readLBL.sh science.txt
Text read from file science.txt: 58050364;Tom Jones
Text read from file science.txt: 58050365;Marry Jane
a="science.txt"
from the Linux command line, will set $a equal to science.txt
If you want this permanent, you could perhaps add it to the bottom of one of your linux profiles. For example add it to the bottom of ~/.bashrc

Create parameters for command Linux shell script

Hello I am trying to create parameters for my shell script but I am having trouble.
lets say for example the file is called test.
When I call ./test -parameter1 input_file.txt
I get an error saying 'no such file or directory'.
Here is an example of my code.
#!/bin/sh
if [ "$1" == "parameter" ]
then
while read line
do
#echo "$line"
done <$1
else
echo "Not working"
fi
My over all goal of this is to read in a file of numbers line by line which I have working, then to calculate the average values of the rows or by columns. Which is why I am trying to create parameters so the user will have to specify ./test -rows input_file.txt or ./test -columns input_file.txt
You are using the string -parameter as the input file name. Perhaps you want:
#!/bin/sh
if [ "$1" = "-parameter" ]
then
while read line
do
#echo "$line"
done <$2 # Use $2 instead of $1 here. Or use shift
else
echo "Not working" >&2
fi

How to read each line of a file 1 at a time in BASH [duplicate]

This question already has answers here:
Looping through the content of a file in Bash
(16 answers)
Closed 2 years ago.
I have the following .txt file:
Marco
Paolo
Antonio
I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is $name, the flow is:
Read first line from file
Assign $name = "Marco"
Do some tasks with $name
Read second line from file
Assign $name = "Paolo"
The following reads a file passed as an argument line by line:
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
This is the standard form for reading lines from a file in a loop. Explanation:
IFS= (or IFS='') prevents leading/trailing whitespace from being trimmed.
-r prevents backslash escapes from being interpreted.
Or you can put it in a bash file helper script, example contents:
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
If the above is saved to a script with filename readfile, it can be run as follows:
chmod +x readfile
./readfile filename.txt
If the file isn’t a standard POSIX text file (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
Here, || [[ -n $line ]] prevents the last line from being ignored if it doesn't end with a \n (since read returns a non-zero exit code when it encounters EOF).
If the commands inside the loop also read from standard input, the file descriptor used by read can be chanced to something else (avoid the standard file descriptors), e.g.:
while IFS= read -r -u3 line; do
echo "Text read from file: $line"
done 3< "$1"
(Non-Bash shells might not know read -u3; use read <&3 instead.)
I encourage you to use the -r flag for read which stands for:
-r Do not treat a backslash character in any special way. Consider each
backslash to be part of the input line.
I am citing from man 1 read.
Another thing is to take a filename as an argument.
Here is updated code:
#!/usr/bin/bash
filename="$1"
while read -r line; do
name="$line"
echo "Name read from file - $name"
done < "$filename"
Using the following Bash template should allow you to read one value at a time from a file and process it.
while read name; do
# Do what you want to $name
done < filename
#! /bin/bash
cat filename | while read LINE; do
echo $LINE
done
Use:
filename=$1
IFS=$'\n'
for next in `cat $filename`; do
echo "$next read from $filename"
done
exit 0
If you have set IFS differently you will get odd results.
Many people have posted a solution that's over-optimized. I don't think it is incorrect, but I humbly think that a less optimized solution will be desirable to permit everyone to easily understand how is this working. Here is my proposal:
#!/bin/bash
#
# This program reads lines from a file.
#
end_of_file=0
while [[ $end_of_file == 0 ]]; do
read -r line
# the last exit status is the
# flag of the end of file
end_of_file=$?
echo $line
done < "$1"
If you need to process both the input file and user input (or anything else from stdin), then use the following solution:
#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
read -p "> $line (Press Enter to continue)"
done
Based on the accepted answer and on the bash-hackers redirection tutorial.
Here, we open the file descriptor 3 for the file passed as the script argument and tell read to use this descriptor as input (-u 3). Thus, we leave the default input descriptor (0) attached to a terminal or another input source, able to read user input.
For proper error handling:
#!/bin/bash
set -Ee
trap "echo error" EXIT
test -e ${FILENAME} || exit
while read -r line
do
echo ${line}
done < ${FILENAME}
Use IFS (internal field separator) tool in bash, defines the character using to separate lines into tokens, by default includes <tab> /<space> /<newLine>
step 1: Load the file data and insert into list:
# declaring array list and index iterator
declare -a array=()
i=0
# reading file in row mode, insert each line into array
while IFS= read -r line; do
array[i]=$line
let "i++"
# reading from file path
done < "<yourFullFilePath>"
step 2: now iterate and print the output:
for line in "${array[#]}"
do
echo "$line"
done
echo specific index in array: Accessing to a variable in array:
echo "${array[0]}"
The following will just print out the content of the file:
cat $Path/FileName.txt
while read line;
do
echo $line
done

Resources