How do I create a Bash script that takes a file name as input? Then, if that file exists, it should print "File exists"; if not, print "File does not exist".
For example, if I ran ./do-i-exist.sh ./do-i-exist.sh
, the output should be only 'File exists'
file="$1"
read answer
if [ $file != -$2 ]
then
echo "File exists"
else
echo "File does not exist"
fi
This is what I'm working with but is not working for me, whenever I add an extension like .sh, .txt or something similar it won't find the file.
CodePudding user response:
The test if a file exists can be done like this
if [ -f "$file" ]
then
This tests for a regular file, not for other kinds of files like a directory.
CodePudding user response:
This is how you can do it. Pass the name of the file while like ./do-i-exist.sh file_path
.
if [ -f "$1" ]
then
echo "File Exists"
else
echo "File does not exist"
fi
CodePudding user response:
First of all, I want to thank anyone and everyone who tried to help. After 3 hard working days, I found the answer, here it is:
#!/bin/bash
file="$@"
if [ -f $file ]
then
echo "File exists"
else
echo "File does not exist"
fi
Using this table:
Variable Name | Description |
---|---|
$0 |
The name of the Bash script |
$1 - $9 |
The first 9 arguments to the Bash script |
$# |
Number of arguments passed to the Bash script |
$@ |
All arguments passed to the Bash script |
$? |
The exit status of the most recently run process |
$$ |
The process ID of the current script |
$USER |
The username of the user running the script |
$HOSTNAME |
The hostname of the machine |
$RANDOM |
A random number |
$LINENO |
The current line number in the script |
I and other users were focused on using $1
from my understanding this refers to the first argument passed to the script but for some reason, it wasn't working since it needed to pass more inputs.
As from my previous comments I didn't have control over the input. The input was hidden in a locked file, and I needed to feed my script to it.
From what we know $0
is only used to check for the file names, $1
to get the first statement and $@
will just take anything(I guess).
I know absolutely nothing about bash and it was the first time ever using it, which is why it took me 3 days to solve this puzzle. This was part of a CTF and just like me, many others may struggle in the future to understand or know how to make a script that will just adapt to a series of inputs from a second script.
This is how it was supported to work:
I was given access to a very restricted server and on this server, I was given the encrypted-file.sh
file. This file was supposed to be fed to /path/to/myfile.sh
then encrypted-file.sh
would execute a second command to open a third locked file hiding a flag on it.
This only works with the right bash file using the right variables on it for encrypted-file.sh
to run without errors, which is what I accomplished here.