Storing directory as a variable for later use in linux script - linux

In my script, I am holding the location (path) of a file as a variable.
For example, fileA
An example of its contents are
fileA=/usr/anotherfolder/somefold/"filenamehere"
However, when i call a command on the file in the script such as:
cat $fileA
or
cat "$fileA"
I get an error saying the file or directory doesn't exist. If I echo $fileA to see what the output is, and then run a cat manually from the terminal, it works fine, don't know what is going wrong. Any help?
Some debug info:
fileA='/home/jacob/Desktop/CS35L/WORK/2/hw/test3/"new"'
echo '/home/jacob/Desktop/CS35L/WORK/2/hw/test3/"new"'
/home/jacob/Desktop/CS35L/WORK/2/hw/test3/"new"
'[' '!' -r '/home/jacob/Desktop/CS35L/WORK/2/hw/test3/"new"' ']'
For these particular lines
Check for readable file
echo $fileA
if [ ! -r "$fileA" ]
then
o=`expr $o + 1`
echo "$fileA not readable."
continue
fi

If file name is new(not "new"), then change
fileA='/home/jacob/Desktop/CS35L/WORK/2/hw/test3/"new"'
to
fileA=/home/jacob/Desktop/CS35L/WORK/2/hw/test3/new

Related

Why is a part of the code inside a (False) if statement executed?

I wrote a small script which:
prints the content of a file (generated by another application) on paper with a matrix printer
prints the same line into a backup file
removes the original file.
The script runs every minute by a cronjob and works fine as long as there are files to print. If there are no files to print, it prints an empty line on the matrix printer and in the backup file. I don't understand why this happens as i implemented an if statement which checks if there is a file to print before the print command is executed. This behaviour only happens if the script is executed by the cron and not if i execute it manually with ./script.sh. What's the reason of this? and how can i solve it?
Something i noticed on the side is that if I place an echo "hi" command in the script, its printed to the matrix printer and the backup file. I expected that its printed to the console console when it has no >> something behind. How does this work?
The script:
#!/bin/bash
# Make sure the backup directory exists
if [ ! -d /home/user/backup_logprint ]
then
mkdir /home/user/backup_logprint
fi
# Print the records if there are any
date=`date +%Y-%m-%d`
filename='_logprint_backup'
printer_path="/dev/usb/lp0"
if [ `ls /tmp/ | grep logprint | wc -l` -gt 0 ]
then
for f in `ls /tmp | grep logprint`
do
echo `cat /tmp/$f` >> "/home/user/backup_logprint/$date$filename"
echo `cat /tmp/$f` >> $printer_path
rm "/tmp/$f"
done
fi
There's no need for ls or an if statement. Just use a proper glob in the for loop, and if no file match, the loop won't be entered.
#!/bin/bash
# Don't check first; just let mkdir decide if
# anything actually needs to be created.
d=/home/user/backup_logprint
mkdir -p "$d"
filename=$(date +"$d/%Y-%m-%d_logprint_backup")
printer_path="/dev/usb/lp0"
# Cause non-matching globs to expand to an empty
# sequence instead of being treated literally.
shopt -s nullglob
for f in /tmp/*logprint*; do
cat "$f" > "$printer_path" && mv "$f" "$d"
done

In output, echo command printed new line when after printed variable

This is my small bash script code and i want to print the number of files created in the directory :
#! /bin/sh
home_dir=/home/var/foo
Count= ls /$home_dir|wc -l
echo -e "$Count files are existed in the directory $home_dir"
exit 0
My expected output is :
9 files are existed in the directory /home/var/foo
but i got the below output:
9
files are existed in the directory /home/var/foo
can you help what went wrong in my above code? Also please suggest if this is the correct way to print the number of files in the directory
This works for me:
Count=$(ls /$xml_dir|wc -l)
To print on the same line
echo -ne "$Count files are existed in the directory $home_dir"
Add argument n to the echo.

Linux script throwing error though it completely looks fine

I have to write Linux script for below question
Write a script that renames files based on the file extension.  The script should prompt the user  for a file extension.  
Next, it should ask the user what prefix to prepend to the file name(s).  By  default the prefix should be the current date in YYYY­MM­DD format.  
So, if the user simply  presses enter the date will be used.  Otherwise, whatever the user entered will be used as the  prefix.  
Next, it should display the original file name and the new name of the file.  Finally, it  should rename the file. 
I wrote below shell script & its throwing error. To me script looks completely fine. Though I am able to write alternative script but Could someone please suggest reason & resolution of error in this script.
Script:
#!/bin/bash
read -p "Please enter a file extension : " EXT
for f in *.${EXT}
do
read -p "Please enter a file prefix (Press ENTER to prefix current Date) :" PREFIX
if [ -z "PREFIX" ]
then
new = "$(date +"%Y-%M-%d")-$(basename ${f})"
mv $f $new
echo "$f renamed to $new"
else
new = "${PREFIX}-${f}"
mv $f $new
echo "$f renamed to $new"
fi
done
Error :
./new.sh: line 13: new: command not found
BusyBox v1.24.2 (2017-05-25 17:33:59 CEST) multi-call binary.
Usage: mv [-fin] SOURCE DEST
or: mv [-fin] SOURCE... DIRECTORY
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY
-f Don't prompt before overwriting
-i Interactive, prompt before overwrite
-n Don't overwrite an existing file
*.png renamed to
[root#localhost ~]#
[root#localhost ~]#
The spaces are spoiling your script during assignment
#new = "$(date +"%Y-%M-%d")-$(basename ${f})"
new="$(date +"%Y-%M-%d")-$(basename ${f})"
also
#new = "${PREFIX}-${f}"
new="${PREFIX}-${f}"
shellcheck is an excellent tool for a basic shell checking

Linux shell script to copy last lines of a file in a directory to append to a file in another directory

I have written the below shell script to copy the last lines of a file in a directory to append to a file in another directory
cd /opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/Lg2Logs
GrinderLG1='rm101sys1lweb22'
GrinderLg2='rm101sys1lweb23'
fileCount=$(ls -l|wc -l)
echo $fileCount
for (( c=0; c<=$fileCount-2; c++ ))
do
Lines=$(more $GrinderLg2"-"$c"-data.log"|wc -l)
Lines1=`expr $Lines - 1`
`"tail -"$Lines1"f /opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/Lg2Logs/"$GrinderLg2"-"$c"-data.log>>/opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/"$GrinderLG1"-"$c"-data.log"`
#exec $command
done
When I am executing this script it says no such file or directory at tail command. Actually both the files exist. Please help.
`"tail -"$Lines1"f /opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/Lg2Logs/"$GrinderLg2"-"$c"-data.log>>/opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/"$GrinderLG1"-"$c"-data.log"`
change to
tail -"$Lines1"f /opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/Lg2Logs/"$GrinderLg2"-"$c"-data.log>>/opt/grinder/svn/IAVS/GrinderLogs/GrinderBaseLogs/"$GrinderLG1"-"$c"-data.log
should work.
In my setup i have tested as below way
#!/bin/sh
`"tail -10f filename"`
give error filename not found
But
#!/bin/sh
tail -10f filename
This works fine.

root running cron task can't read .txt file generated by www-data user

I have a simple php page that writes a file to my server.
// open new file
$filename = "$name.txt";
$fh = fopen($filename, "w");
fwrite($fh, "$name".";"."$abbreviation".";"."$uid".";");
fclose($fh);
I then have a cron job that I know runs as root as test that and need that.
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi
The cronjob is a bash script that can detect the file exists, but it can't seem to read the contents of the file.
#!/bin/bash
######################################################
#### Loop through the files and generate coincode ####
######################################################
for file in /home/test/customcoincode/queue/*
do
echo $file
chmod 777 $file
echo "read file"
while read -r coinfile; do
echo $coinfile
echo "Assign variables from file"
#############################################
#### Set the variables to from the file #####
#############################################
coinName=$(echo $coinfile | cut -f1 -d\;)
coinNameAbreviation=$(echo $coinfile | cut -f2 -d\;)
UId=$(echo $coinfile | cut -f3 -d\;)
done < $file
echo "`date +%H:%M:%S` - $coinName : Your Kryptocoin is being compiled!"
echo $file
echo "copy $coinName file to generated directory"
cp -b $file /home/test/customcoincode/generatedCoins/$coinName.txt
echo "`date +%H:%M:%S` : Delete queue file"
# rm -f $file
done
echo $file recognises the file exists
echo $coinfile is blank
Yet when I nano ./coinfile.txt in terminal I can see clearly there is text in there
I run ls -l and I see that the file has the permissions
-rw-r--r-- 1 www-data www-data
I was under the impression that this would still mean the file can be read by other users?
Do I need to be able to execute the file if i am opening it and reading the contents?
Any advice would be greatly appreciated. I can expand and show my code if you want, but it was working before when I called a bash script to write the file... and that time it would save the file under root user with rwx for most and then could be read. But this then caused other issues in the php page, so is not an option.
You have:
while read -r coinfile; do
...
I see no indication that you're reading from $file. The command
read -r coinfile
will simply read from standard input (the -r merely affects the treatment of backslashes). In a cron job, if I recall correctly, standard input is empty or unavailable, which would explain why $coinfile is empty.
If you actually do read from $file -- for example, if your real code looks something like:
while read -r coinfile; do
...
done <$file
then you need to show us your entire script, or at least a self-contained version of it that exhibits the problem. Actually, you need to show us your entire script whether that's the problem or not.
http://sscce.org/

Resources