Run non-rooted commands

On linux based some commands that you install without root like brew packages and you sometimes need to run them with sudo for that, I made this script

#!/bin/bash

secure_path=(“/usr/local/sbin” “/usr/local/bin” “/usr/sbin” “/usr/bin” “/sbin/bin” “…


This content originally appeared on DEV Community and was authored by Jaipal001

On linux based some commands that you install without root like brew packages and you sometimes need to run them with sudo for that, I made this script

#!/bin/bash

secure_path=("/usr/local/sbin" "/usr/local/bin" "/usr/sbin" "/usr/bin" "/sbin/bin" "/snap/bin") # snap for ubuntu based

if [[ ! $(which $1) ]]; then
    $@  # if does not exist, run them and get error of command not exist and get exit 1
    exit 1 # just in case program moves to next line, exit 1
fi
global_found=
# some would say just do sudo $@ but what if after exitting the app/command, it return a non-0 status? so we better do this
for item in "${secure_path[@]}"; do
    # if found stop
    if [[ $(which $1) == $item/$1 ]]; then
        echo exist $item/$1
        global_found=1
        break
    fi
done
if [[ ! $global_found ]]; then
    sudo -E $(which $1) $(echo $@ | sed 's/'$1' //') # trim 1st argument of our script
else
    sudo $@ # $@ means all bash script arguments
fi


This content originally appeared on DEV Community and was authored by Jaipal001


Print Share Comment Cite Upload Translate Updates
APA

Jaipal001 | Sciencx (2025-10-19T08:50:03+00:00) Run non-rooted commands. Retrieved from https://www.scien.cx/2025/10/19/run-non-rooted-commands/

MLA
" » Run non-rooted commands." Jaipal001 | Sciencx - Sunday October 19, 2025, https://www.scien.cx/2025/10/19/run-non-rooted-commands/
HARVARD
Jaipal001 | Sciencx Sunday October 19, 2025 » Run non-rooted commands., viewed ,<https://www.scien.cx/2025/10/19/run-non-rooted-commands/>
VANCOUVER
Jaipal001 | Sciencx - » Run non-rooted commands. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/19/run-non-rooted-commands/
CHICAGO
" » Run non-rooted commands." Jaipal001 | Sciencx - Accessed . https://www.scien.cx/2025/10/19/run-non-rooted-commands/
IEEE
" » Run non-rooted commands." Jaipal001 | Sciencx [Online]. Available: https://www.scien.cx/2025/10/19/run-non-rooted-commands/. [Accessed: ]
rf:citation
» Run non-rooted commands | Jaipal001 | Sciencx | https://www.scien.cx/2025/10/19/run-non-rooted-commands/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.