How can I keep file name to variable from this code - linux

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

Related

Is there a way to pipe user input within a bash script into the cat command and have it save at a destination of my choosing as a text file

Something similar to this maybe:
#! /bin/bash
echo What is your name?
read name | cat > ~/Documents/file.txt
if [[ $name==Bob ]]
echo something
fi
The command creates an empty file on manjaro mint.
Your problem is that read doesn't create any output.
And you have a syntax error further down the line, it would be a good idea to put your script(s) through shellcheck.
#! /bin/bash
echo What is your name?
read -r name
echo "$name" > ~/Documents/file.txt
if [[ "$name" == "Bob" ]]; then
echo something
fi

Run commands from a text file through a bash script

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.

trying to read every line in file, output always 'cat $file'

I am trying to display every line of a file in the terminal but the output is always:
cat $file
this is my code:
#!/bin/bash
file="users.csv"
IFS=''
echo "bobama, Barack Obama" > $file
echo "gbush, George Bush" >> $file
for line in `cat $file`;
do
echo $line;
done
I solved it by replacing 'cat $file' with $(cat $file).
You can find a better explanation here:
Why can't you use cat to read a file line by line where each line has delimiters

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

basic bash syntax issue - syntax error near unexpected token

I think my script does what its meant to do, at first I just had
#!/bin/bash
for file in /home/parallels/Desktop/trashcan/*
do
echo "Would you like to delete - " $file
done
I then wanted to add the obvious missing functionality so I now have
#!/bin/bash
for file in /home/parallels/Desktop/trashcan/*
do
echo "Would you like to delete - " $file
read line
if [$line == y|Y]
sudo rm $file
fi
done
Thats where I'm at now, I did at first try to use a case statement instead of the if as I have a working script with the case statement I'd need but simply copying it over gives me the same error - syntax error near unexpeted token, I get this for fi and done
[ is a command, so it must be separated by whitespace from its first argument:
if [ "$line" = y ] || [ "$line" = Y ]; then
sudo rm "$file"
fi
If you are using bash, you can replace the standard usage shown above with the more concise
if [[ $line = [yY] ]]; then
sudo rm "$file"
fi
As Keith Thompson pointed out, only an answer of exactly 'y' or 'Y' will allow the file to be removed. To allow 'yes' or 'Yes' as well, you can use
shopt -s extglob
if [[ $line = [yY]?(es) ]]
(The shopt line is only required for earlier versions of bash. Starting with version 4, extended patterns are the default in a conditional expression.)
The if part should be
if [ "$line" = "y" ] || [ "$line" = "Y" ]
then
sudo rm $file
fi
I faced similar problem. I had opened the .sh file in windows and Windows has added CRLF at the end of every line.
I found this out by running
cat --show-nonprinting filename.extension
E.g.
cat --show-nonprinting test.sh
Then, I converted it using
dos2unix filename.extension
E.g.
dos2unix myfile.txt
dos2unix myshell.sh

Resources