Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
the below function is not working is the file has some blank spaces or tabs.
get_value()
{
file="/u01/app/file.lst"
if [ -f $file ];
then
echo "file.lst file exists, Checking values"
if [ -s $file ];
then
while IFS= read -r value
do
variable=`echo $value`
done < "$file"
echo "Variable values is : $variable"
else
echo "file.lst file is empty,Default value for variable is 10"
variable=10
echo $variable
fi
else
echo "file.lst file doesnot exists, ,Default value for variable is 10"
variable=10
echo $variable
fi
}
pls help how to check file contents with blank spaces also
If there is only one line in a file then a while loop is not needed. Something like:
#!/usr/bin/env bash
get_value(){
local variable file
file="/u01/app/file.lst"
if [[ ! ( -e $file && -f $file ) ]]; then
variable=10
printf '%s does not exists, Default value for variable is %d\n' "${file##*/}" "$variable"
printf 'Variable value is: %d\n' "$variable"
return
fi
IFS= read -r variable < "$file"
if [[ -z $variable ]]; then
variable=10
printf '%s is empty, Default value for variable is %d\n' "${file##*/}" "$variable"
printf 'Variable value is: %d\n' "$variable"
return
fi
printf 'Variable value is: %s\n' "$variable"
}
get_value
The default value for the variable can be done with a Shell Parameter Expansion with "${variable:-10}"
The if clause/statement can be replace with a command grouping via the curly braces { } something like: [[ ... ]] && { command-goes-and-other-things-here; }
Related
I am trying to check if the string is in format in shell script.
below is the code i am trying and the output i want to get.
Format: <datatype>(length,length) | <datatype>(length,length)
I have multiple cases with this scenario, if both datatypes have () then it should show pass, else fail.
Eg. decimal(1,0)|number(11,0) this should pass but int|number(11,0) or decimal(1,0)|int should fail.
Code1:
INPUT='decimal(1,0)|number(11,0)'
sub="[A-Z][a-z]['!##$ %^&*()_+'][0-9][|][A-Z][a-z]['!##$ %^&*()_+'][0-9][|]"
if [ "$INPUT" == "$sub" ]; then
echo "Passed"
else
echo "No"
fi
Code 2:
INPUT='decimal(1,0)|number(11,0)'
sub="decimal"
if [ "$INPUT" == *"("*") |"*"("*") " ]; then
echo "Passed"
else
echo "No"
fi
Any help will be fine. Also note, I am very new to shell scripting.
Reading both values into variables, first removing alpha characters and then checking variables are not empty
result='FAIL'
input='int|number(6,10)'
IFS="|" read val1 val2 <<<"$(tr -d '[:alpha:]' <<<"$input")"
if [ -n "$val1" ] && [ -n "$val2" ]; then
result='PASS'
fi
echo "$result: val1='$val1' val2='$val2'"
Result:
FAIL: val1='' val2='(6,10)'
For input='decimal(8,9)|number(6,10)'
PASS: val1='(8,9)' val2='(6,10)'
That looks like just a simple regex to write.
INPUT='decimal(1,0)|number(11,0)'
if printf "%s" "$INPUT" | grep -qEx '[a-z]+\([0-9]+,[0-9]+\)(\|[a-z]+\([0-9]+,[0-9]+\))*'; then
echo "Passed"
else
echo "No"
fi
Try to figure out how to apply conditions to two variables, one of them read from file and stored into array.
Seems that the problem is the second variable, the one stored into array.
#!/bin/bash
#CHECKTIME
#GET TIME
IFS=- read -r DAY HOUR MINUTE < <(date +%u-%H-%M)
echo $DAY
echo $HOUR
echo $MINUTE
arr=()
while IFS= read -r line; do
arr+=("$line")
done < myFile.txt
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}
if [ $DAY = $arr[0]]
then
echo "do event"
else
echo "don't do event"
fi
Thanks
The syntax for getting an element of an array is this:
${arr[0]}
Although that's not the only problem with your script. You could use ShellCheck to debug the rest. To start, [ $DAY = $arr[0]] is invalid.
You are mixing zsh and bash syntax here. You if statement would be valid under zsh (although in zsh it should be $arr[1] instead of $arr[0]). In bash, you can do either
if [ "$DAY" = "${arr[0]}" ]
or (if you don't like quoting)
if [[ $DAY == ${arr[0]} ]]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
#!/bin/bash
clear
character=0
word=0
line=`echo -e "\n"`
space=`echo -e " "`
if [ $# -eq 0 ]
then
echo "You haven't entered any line"
elif [ $# -eq 1 ]
then
filename=$1
while read -n1 newline
do
if [ '$newline' == '$line' ]
then
((line++))
elif [ '$newline' == '$space' ]
then
((word++))
else
((character++))
fi
done < $filename
echo "No of line =$line"
echo "No of word =$word"
echo "No of character =$character"
fi
Double quotes around a variable are OK, but don't put single quotes around each variable as was done here:
if [ '$newline' == '$line' ]
To see why that fails, look at the following code, where the pale blue text is code, and the pink text is output:
a=3
echo $a
3
echo '$a'
$a
if [ '$a' == 3 ] ; then echo true ; else echo false ; fi
false
if [ $a == 3 ] ; then echo true ; else echo false ; fi
true
Are you aware of what single quotes do? It prevents any escaping, or string substitution from occurring. In other words, it denotes raw string (you can't even put a single quote inside a single quote!).
You should change to double quotes if you want variable expansion inside:
if [ "$newline" == "$line" ]
# ^ ^ ^ ^
#!/bin/bash
WC=$(cat $1 | wc -mlw)
echo "No of line =$(echo $WC | awk '{print $1}')"
echo "No of word =$(echo $WC | awk '{print $2}')"
echo "No of character =$(echo $WC | awk '{print $3}')"
This question already has answers here:
A variable modified inside a while loop is not remembered
(8 answers)
Closed 6 years ago.
I'm trying to loop through allURLs.txt and check if every entry in that file exists in PDFtoCheck.pdf. I know of a tool called pdfgrep, but can't seem to apply it to suit my objective.
#!/bin/bash
entriesMissing=0;
cat allURLs.txt | while read line
do
# do something with $line here
if [ ! -z echo `pdfgrep "$line" PDFtoCheck.pdf` ];
then
echo "yay $line";
else
echo "$line not found";
entriesMissing=$[$entriesMissing+1];
fi
done
echo "DONE";
echo "There are $entriesMissing entries missing!";
Despite placing dummy values in allURLs.txt, entires which are present in allURLs.txt but not in PDFtoCheck.pdf are not reflected in the output. Any idea how to make it work as intended?
Please note that a subshell is created when piping: cat file | while. You should use file redirection instead: while ... do; done < file.
As far as I can see pdfgrep supports the -q quiet flag, so you can just use it in the if-statement.
entriesMissing=0
while IFS= read -r line; do
if pdfgrep -q -- "$line" PDFtoCheck.pdf; then
printf "Found '%s'\n" "$line"
else
printf "'%s' not found\n" "$line"
((entriesMissing++))
fi
done < allURLs.txt
printf "There are %d entries missing\n" "%entriesMissing"
I also changed the increment to ((... ++))
Extending my comment as answer. I'm using -c option which is also available in pdfgrep :
entriesMissing=0
while read line
do
# do something with $line here
if [ $(grep -c "$line" b) -eq 0 ]
then
((entriesMissing++))
echo "$line not found"
else
echo "yay $line"
fi
done < allURLs.txt
echo "DONE"
echo "There are $entriesMissing entries missing!";
One thing I want point out in your code that you are incrementing entriesMissing inside a subshell(pipe) which doesn't get reflected at the last line. Hope it helps.
I've been stuck for quite some time with the following code. It works but the variable loses the value that was set during the iterations.
I have the following code
mistakes=0
entered_chars=()
word_length=0
answer=""
answer_guess=""
checkIfLetterInsideWord(){
exists=0
letter=$2
word_array=`echo $1 | grep -o . `;
for (( i=1; i <= $word_length; i++))
do
if [[ "${1:$i-1:1}" = ${letter} ]]; then
exists=1
answer_guess=$(echo $answer_guess | sed "s/-/${letter}/{i}" )
fi
done
echo $exists
}
askUserInput(){
answer=$answer
echo $answer
echo "Please type a letter"
read user_input
if [ ! -z $user_input ]; then
user_input=$(echo $user_input | tr '[:upper:]' '[:lower:]')
if [ $(checkIfAlreadyEntered "$user_input") -eq 0 ]; then
if [ $(checkIfLetterInsideWord $answer $user_input) -eq 0 ]; then
mistakes=$((mistakes + 1)); fi
echo "Current mistake count; $mistakes "
entered_chars+=($user_input)
else
echo "Char has already been entered"
fi
else
echo "You haven't entered any input!"
fi
}
guessTheWord() {
answer=$OPTARG
word_length=$(printf $answer | wc -m)
temp=$(echo $answer | sed 's/\(.\)/\1 /g')
array=($temp)
echo "The chosen word is $word_length long"
gameOngoing=true
for(( i=1; i<=$word_length; i++)) do
answer_guess="$answer_guess-"
done
while $gameOngoing
do
echo $answer_guess
askUserInput $answer
done
}
I want to preserve the value of the variable answer_guess. I understand that it loses the value because of the usage of a pipeline inside the loop but I don't know to approach this problem.
The problem has nothing do to with the pipe. Rather, it is that you call checkIfLetterInsideWord inside a command-substitution ($(...)). Command substitution executes in a subshell so environment changes in the function will not persist.
It would be better to rewrite checkIfLetterInsideWord so that it returns an exit status. Something like:
if [[ $exists ]]; then
return 0 # Success
else
return 1 # Failure
end
Then you could simply call it without worrying about a subshell:
if checkIfLetterInsideWord "$answer" "$user_input"; then
# letter is in word
else
# letter is not in word
fi
There are other issues with the code. I've limited this answer to the question about preserving the value of variables.
answer_guess=$(echo $answer_guess | sed "s/-/${letter}/{i}" )
replace the - with .
so your code becomes
answer_guess=$(echo $answer_guess | sed "s/./${letter}/{i}" )