How check user ID on bash and deny run from root
- User
How check user ID on bash and deny run from root
- Assistant
In a Bash script, you can check the user ID (UID) and prevent the script from being executed as the root user (UID 0) using conditional statements. Here's a simple example:
bash#!/bin/bash # Check if the script is run as root if [ "$EUID" -eq 0 ]; then echo "This script cannot be run as root. Please run it as a regular user." exit 1 fi # Your script logic goes here echo "Running script as a non-root user."Explanation:
-
$EUID: This variable holds the effective user ID of the current user. It is preferred over because may not reflect a user's effective user ID in some scenarios (like using ).
-
- User
Check if correct number of arguments is provided
if [ # -lt 1 ] || [ # -gt 2 ]; then echo "Usage: $0 <plus|minus> [step]" exit 1 fi
How to check for 5 arguments instead of 2
- Assistant
To check for exactly 5 arguments instead of 2 in your Bash script, you would modify the conditional statement that checks the number of arguments passed to the script. Here's how you can do it:
bash# Check if exactly 5 arguments are provided if [ $# -ne 5 ]; then echo "Usage: $0 <arg1> <arg2> <arg3> <arg4> <arg5>" exit 1 fiExplanation:
$#: This variable contains the number of arguments passed to the script.-ne: This stands for "not equal". We use this operator to check if the number of arguments is not equal to 5.echo: If the condition is true, an informative message is printed, specifying the correct usage of the script.exit 1: Exits the script with a status code of 1, indicating an error.
- User
How get dir of script in bash
- Assistant
In Bash, you can get the directory of the currently executing script using the special variable
$0along with thedirnamecommand. Here’s how you can do it:bash#!/bin/bash # Get the directory of the script SCRIPT_DIR="$(dirname "$(realpath "$0")")" # Alternatively, if you don't want to use realpath (which may not be available) # SCRIPT_DIR="$(dirname "$0")" echo "Script directory: $SCRIPT_DIR"Explanation:
$0: This variable contains the name of the script as it was called. It can be a relative or absolute path.- : This command resolves the full path of the script. It converts any relative paths to absolute ones and resolves symbolic links.