Useful CLI tools (bash) for Arch Linux administration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

840 lines
23 KiB

6 years ago
  1. #!/bin/bash
  2. # Global bash customization settings
  3. # Copyright (C) 2018 Pekka Helenius
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. ##############################################################################
  18. # In order to use this file, replace the following line in /etc/bash.bashrc file:
  19. # PS1="[\\u@\\h \\W]\\$ "
  20. #
  21. # with
  22. #
  23. # [[ -f /etc/bash.custom ]] && . /etc/bash.custom || PS1="[\\u@\\h \\W]\\$ "
  24. # Insert/Install this file into /etc folder.
  25. # After that, you can change bash settings globally by editing /etc/bash.custom file
  26. ##############################################################################
  27. # Check https://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html for more settings
  28. #######################################
  29. # Use server environment settings? Main switch.
  30. # Use only if you implement this solution to a server environment
  31. # You don't need this feature for client/local computers
  32. ENABLE_SERVER_ENV=no
  33. #######################################
  34. # APPLIES ONLY IF SERVER ENVIRONMENT ENABLED
  35. # Retrieve time zone information for every user connected with a SSH client
  36. # Based on a look up for local GeoIP database
  37. # If timezone can't be defined, use UTC time as a fallback value
  38. # Timezone information can be overwritten by exporting TZ variable with
  39. # desirable value as the user in the user-specific $HOME/.bashrc file
  40. #
  41. # This method doesn't require any environment variables delivered via SSH
  42. # connection by a client
  43. # This method doesn't require any modifications to /etc/ssh/sshd_config file.
  44. #
  45. ENABLE_SSH_TIMEZONE=yes
  46. #######################################
  47. # APPLIES ONLY IF SERVER ENVIRONMENT ENABLED
  48. # If server environment is enabled
  49. if [[ $ENABLE_SERVER_ENV == "yes" ]]; then
  50. if [[ $ENABLE_SSH_TIMEZONE == "yes" ]]; then
  51. if [[ $(export -p | grep SSH_TTY) ]]; then
  52. . $(which ssh_timezone)
  53. fi
  54. fi
  55. fi
  56. ##############################################################################
  57. # Hook to bash's STDERR output so that it will be printed as red for all users
  58. export LD_PRELOAD="/usr/\$LIB/libstderred.so${LD_PRELOAD:+:$LD_PRELOAD}"
  59. ##############################################################################
  60. # COLOR TABLE
  61. # These are available colors
  62. # Expand if you wish
  63. # Full color table available by executing 'tputcolors' command
  64. # To get equal color values here, use command 'tput setaf <colorcode> | hexdump -c'
  65. # By default, blank TTY sessions have TERM=linux, which has limitation of 8 possible colors when
  66. # tput is used. On many graphical environments, TERM=xterm-256color is used instead, expanding
  67. # all possible colors to 256.
  68. # Because colors defined in this bash file rely on 256 color support, we must
  69. # export TERM=xterm-256color in all opened shell sessions, including blank TTYs.
  70. #
  71. # Setting raw color values, which are disabled below, does not work well with
  72. # slash \$ escaped 'bash_foldercolor' function (defined below)
  73. #
  74. # You get count of supported colors with 'tput colors' command
  75. #
  76. export TERM=xterm-256color
  77. bash_red=$(tput setaf 196)
  78. bash_pink=$(tput setaf 211)
  79. bash_green=$(tput setaf 46)
  80. bash_yellow=$(tput setaf 226)
  81. bash_light_yellow=$(tput setaf 229)
  82. bash_gold=$(tput setaf 184)
  83. bash_orange=$(tput setaf 172)
  84. bash_blue=$(tput setaf 27)
  85. bash_light_blue=$(tput setaf 33)
  86. bash_magenta=$(tput setaf 201)
  87. bash_cyan=$(tput setaf 51)
  88. bash_turquoise=$(tput setaf 86)
  89. bash_grey=$(tput setaf 250)
  90. bash_white=$(tput setaf 255)
  91. bash_color_default=$(tput sgr0)
  92. #bash_red="\033[38;5;196m"
  93. #bash_pink="\033[38;5;211"
  94. #bash_green="\033[38;5;46m"
  95. #bash_yellow="\033[38;5;226m"
  96. #bash_light_yellow="\033[38;5;229m"
  97. #bash_gold="\033[38;5;184m"
  98. #bash_orange="\033[38;5;172m"
  99. #bash_blue="\033[38;5;27m"
  100. #bash_light_blue="\033[38;5;33m"
  101. #bash_magenta="\033[38;5;201m"
  102. #bash_cyan="\033[38;5;51m"
  103. #bash_turquoise="\033[38;5;86m"
  104. #bash_grey="\033[38;5;250m"
  105. #bash_white="\033[38;5;255m"
  106. #bash_color_default="\033[0m"
  107. ##############################################################################
  108. # COLOR TABLE CHECK FUNCTION
  109. bash_colorstring() {
  110. case $1 in
  111. red)
  112. printf "\x01%s\x02" "${bash_red}"
  113. ;;
  114. pink)
  115. printf "\x01%s\x02" "${bash_pink}"
  116. ;;
  117. green)
  118. printf "\x01%s\x02" "${bash_green}"
  119. ;;
  120. yellow)
  121. printf "\x01%s\x02" "${bash_yellow}"
  122. ;;
  123. light_yellow)
  124. printf "\x01%s\x02" "${bash_light_yellow}"
  125. ;;
  126. gold)
  127. printf "\x01%s\x02" "${bash_gold}"
  128. ;;
  129. orange)
  130. printf "\x01%s\x02" "${bash_orange}"
  131. ;;
  132. blue)
  133. printf "\x01%s\x02" "${bash_blue}"
  134. ;;
  135. light_blue)
  136. printf "\x01%s\x02" "${bash_light_blue}"
  137. ;;
  138. magenta|purple)
  139. printf "\x01%s\x02" "${bash_magenta}"
  140. ;;
  141. cyan)
  142. printf "\x01%s\x02" "${bash_cyan}"
  143. ;;
  144. turquoise)
  145. printf "\x01%s\x02" "${bash_turquoise}"
  146. ;;
  147. grey)
  148. printf "\x01%s\x02" "${bash_grey}"
  149. ;;
  150. white)
  151. printf "\x01%s\x02" "${bash_white}"
  152. ;;
  153. default|*)
  154. printf "\x01%s\x02" "${bash_color_default}"
  155. esac
  156. }
  157. ##############################################################################
  158. # Original PS1 variable value
  159. #PS1='[\u@\h \W]\$ '
  160. #######################################
  161. # APPLIES ONLY IF SERVER ENVIRONMENT ENABLED
  162. # Different command prompt for local (server) logins?
  163. # Distinguish from SSH logins
  164. # This string does not have any colors for now
  165. # Applies only to tty sessions (sessions without X desktop)
  166. BASH_PS1_DIFFERENT_LOCAL=yes
  167. BASH_PS1_LOCAL='[\u: \W ]\$ '
  168. #######################################
  169. # This is an override switch for all color settings
  170. BASH_PS1_SHOW_COLORS=yes
  171. #######################################
  172. # Start and ending symbols for command prompt
  173. BASH_PS1_START="["
  174. BASH_PS1_START_COLORS=no
  175. BASH_PS1_START_COLOR=$(bash_colorstring default)
  176. BASH_PS1_END=" ]"
  177. BASH_PS1_END_COLORS=no
  178. BASH_PS1_END_COLOR=$(bash_colorstring default)
  179. #######################################
  180. # Override command prompt string?
  181. BASH_PS1_SYNTAX_OVERRIDE=no
  182. BASH_PS1_SYNTAX_OVERRIDESTR='[\u@\h \W]\$ '
  183. #######################################
  184. # Use colors for users?
  185. # Group 'sudo' members are considered as sysadmins.
  186. BASH_USER_COLORS=yes
  187. BASH_SYSADMIN_COLOR=$(bash_colorstring yellow)
  188. BASH_USER_COLOR=$(bash_colorstring default)
  189. BASH_ROOT_COLOR=$(bash_colorstring red)
  190. #######################################
  191. # Use different color for folders owned by the user and some other color for other folders?
  192. BASH_FOLDER_COLORS=yes
  193. BASH_USER_FOLDER_COLOR=$(bash_colorstring green)
  194. BASH_NOTOWNED_FOLDER_COLOR=$(bash_colorstring red)
  195. #######################################
  196. # Colors for ls command?
  197. BASH_LS_COLORS=yes
  198. #######################################
  199. # Show the name of this computer?
  200. BASH_SHOW_HOSTNAME=no
  201. # User and hostname separator settings
  202. BASH_HOSTNAME_SEP="@"
  203. BASH_HOSTNAME_SEP_COLORS=no
  204. BASH_HOSTNAME_SEP_COLOR=$(bash_colorstring gold)
  205. # Use color for hostname?
  206. BASH_HOSTNAME_COLORS=yes
  207. BASH_HOSTNAME_COLOR=$(bash_colorstring blue)
  208. #######################################
  209. # Hostname/user and folder separator settings
  210. BASH_FOLDER_SEP=":"
  211. BASH_FOLDER_SEP_COLORS=no
  212. BASH_FOLDER_SEP_COLOR=$(bash_colorstring default)
  213. #######################################
  214. # Suffix symbol settings
  215. BASH_SUFFIX_SYMBOL="$ "
  216. BASH_SUFFIX_SYMBOL_ROOT="# "
  217. BASH_SUFFIX_COLORS=no
  218. BASH_SUFFIX_COLOR=$(bash_colorstring default)
  219. ##############################################################################
  220. # Timestamp
  221. # Show timestamp in the command prompt?
  222. BASH_SHOW_TIMESTAMP=yes
  223. # Example: 26/02/2018 21:33:19
  224. # "\D{%d/%m/%Y} \t"
  225. # Example: 26/02/2018
  226. # "\D{%d/%m/%Y}"
  227. # Example: 21:33:19
  228. # "\t"
  229. BASH_TIMESTAMP_FORMAT=" \! | \D{%d/%m/%Y} \t"
  230. BASH_TIMESTAMP_COLORS=no
  231. BASH_TIMESTAMP_COLOR=$(bash_colorstring default)
  232. #######################################
  233. # Return codes after command execution
  234. # Show command return code in bash?
  235. USE_RETCODE=yes
  236. # Print human readable text strings for each code?
  237. RETCODE_HUMAN=no
  238. # Use colors in error codes?
  239. RETCODE_COLORS=yes
  240. if [[ $USE_RETCODE == "yes" ]]; then
  241. function RETCODE() {
  242. local RET=$?
  243. case $RET in
  244. 0)
  245. local RETC=$(bash_colorstring green)
  246. local RETH="ok"
  247. ;;
  248. 1)
  249. local RETC=$(bash_colorstring red)
  250. local RETH="error"
  251. ;;
  252. 2)
  253. local RETC=$(bash_colorstring orange)
  254. local RETH="misuse of shell builtin"
  255. ;;
  256. 127)
  257. local RETC=$(bash_colorstring orange)
  258. local RETH="not found"
  259. ;;
  260. 128)
  261. local RETC=$(bash_colorstring red)
  262. local RETH="invalid exit argument"
  263. ;;
  264. 130)
  265. local RETC=$(bash_colorstring purple)
  266. local RETH="aborted"
  267. ;;
  268. *)
  269. local RETC=$(bash_colorstring yellow)
  270. local RETH="undefined exit code"
  271. ;;
  272. esac
  273. if [[ $RETCODE_COLORS == "no" ]]; then
  274. RETC=$(bash_colorstring default)
  275. fi
  276. if [[ $RETCODE_HUMAN == "yes" ]]; then
  277. printf "Return code: ${RETC}$RET - $RETH$(bash_colorstring default)\n"
  278. else
  279. printf "Return code: ${RETC}$RET$(bash_colorstring default)\n"
  280. fi
  281. }
  282. PROMPT_COMMAND=RETCODE
  283. fi
  284. ##############################################################################
  285. # Set up ls command colors
  286. #
  287. if [[ $BASH_PS1_SHOW_COLORS == "yes" ]]; then
  288. if [[ $BASH_LS_COLORS == "yes" ]]; then
  289. eval "$(dircolors -b /etc/dircolors)"
  290. alias ls='ls --color=auto'
  291. fi
  292. fi
  293. #######################################
  294. # Set up starting and ending symbols
  295. #
  296. if [[ $BASH_PS1_START_COLORS == "yes" ]]; then
  297. BASH_PS1_START_INSERT="${BASH_PS1_START_COLOR}${BASH_PS1_START}$(bash_colorstring default)"
  298. else
  299. BASH_PS1_START_INSERT="${BASH_PS1_START}"
  300. fi
  301. if [[ $BASH_PS1_END_COLORS == "yes" ]]; then
  302. BASH_PS1_END_INSERT="${BASH_PS1_END_COLOR}${BASH_PS1_END}$(bash_colorstring default)"
  303. else
  304. BASH_PS1_END_INSERT="${BASH_PS1_END}"
  305. fi
  306. #######################################
  307. # Set up folder-specific colors
  308. #
  309. bash_foldercolor() {
  310. # Change color if we are not owner of the current dir
  311. # For root we always use green color
  312. #
  313. if [[ $BASH_FOLDER_COLORS == "yes" ]]; then
  314. if [[ $(stat -c %u "$PWD") -eq $(id -u) ]] || [[ $(id -u) -eq 0 ]]; then
  315. # Green color
  316. printf "%s" "${BASH_USER_FOLDER_COLOR}"
  317. else
  318. # Red color
  319. printf "%s" "${BASH_NOTOWNED_FOLDER_COLOR}"
  320. fi
  321. else
  322. # White color // reset attributes
  323. printf "%s" "$(bash_colorstring default)"
  324. fi
  325. }
  326. #######################################
  327. # Set up user-specific colors
  328. #
  329. bash_usercolor() {
  330. if [[ $BASH_USER_COLORS == "yes" ]] ;then
  331. if [[ $(id -u) == 0 ]]; then
  332. printf "%s" "${BASH_ROOT_COLOR}"
  333. elif [[ $(groups | grep -o sudo) ]]; then
  334. printf "%s" "${BASH_SYSADMIN_COLOR}"
  335. else
  336. printf "%s" "${BASH_USER_COLOR}"
  337. fi
  338. else
  339. printf "%s" "$(bash_colorstring default)"
  340. fi
  341. }
  342. #######################################
  343. # Set up computer hostname
  344. #
  345. bash_hostname() {
  346. if [[ $BASH_SHOW_HOSTNAME == "yes" ]]; then
  347. if [[ $BASH_HOSTNAME_SEP_COLORS == "yes" ]]; then
  348. BASH_HOSTNAME_SEP_INSERT="${BASH_HOSTNAME_SEP_COLOR}${BASH_HOSTNAME_SEP}$(bash_colorstring default)"
  349. else
  350. BASH_HOSTNAME_SEP_INSERT="${BASH_HOSTNAME_SEP}"
  351. fi
  352. if [[ $BASH_HOSTNAME_COLORS == "yes" ]]; then
  353. printf "%s" "\u$(bash_colorstring default)${BASH_HOSTNAME_SEP_INSERT}${BASH_HOSTNAME_COLOR}\h$(bash_colorstring default)"
  354. else
  355. printf "%s" "\u$(bash_colorstring default)${BASH_HOSTNAME_SEP_INSERT}\h"
  356. fi
  357. else
  358. printf "%s" "\u$(bash_colorstring default)"
  359. fi
  360. }
  361. #######################################
  362. # Set up folder separator
  363. #
  364. bash_folder_separator() {
  365. if [[ $BASH_FOLDER_SEP_COLORS == "yes" ]] && [[ $BASH_SHOW_HOSTNAME == "yes" ]]; then
  366. printf "%s" "${BASH_FOLDER_SEP_COLOR}${BASH_FOLDER_SEP}$(bash_colorstring default)"
  367. else
  368. printf "%s" "${BASH_FOLDER_SEP}"
  369. fi
  370. }
  371. #######################################
  372. # Set up timestamp
  373. #
  374. bash_timestamp() {
  375. if [[ $BASH_SHOW_TIMESTAMP == "yes" ]]; then
  376. if [[ $BASH_TIMESTAMP_COLORS == "yes" ]]; then
  377. printf "%s" "${BASH_TIMESTAMP_COLOR}${BASH_TIMESTAMP_FORMAT}$(bash_colorstring default) - "
  378. else
  379. printf "%s" "${BASH_TIMESTAMP_FORMAT} - "
  380. fi
  381. else
  382. printf ""
  383. fi
  384. }
  385. #######################################
  386. # Set up suffix symbol
  387. #
  388. bash_suffixsymbol() {
  389. if [[ $(id -u) -eq 0 ]]; then
  390. BASH_SUFFIX=${BASH_SUFFIX_SYMBOL_ROOT}
  391. else
  392. BASH_SUFFIX=${BASH_SUFFIX_SYMBOL}
  393. fi
  394. if [[ $BASH_SUFFIX_COLORS == "yes" ]]; then
  395. printf "%s" "${BASH_SUFFIX_COLOR}${BASH_SUFFIX}$(bash_colorstring default)"
  396. else
  397. printf "%s" "${BASH_SUFFIX}"
  398. fi
  399. }
  400. #######################################
  401. # Export command prompt string
  402. #
  403. if [[ $BASH_PS1_SHOW_COLORS != "yes" ]]; then
  404. BASH_PS1_START_COLORS=$(bash_colorstring default)
  405. BASH_PS1_END_COLORS=$(bash_colorstring default)
  406. BASH_USER_COLOR=$(bash_colorstring default)
  407. BASH_ROOT_COLOR=$(bash_colorstring default)
  408. BASH_USER_FOLDER_COLOR=$(bash_colorstring default)
  409. BASH_NOTOWNED_FOLDER_COLOR=$(bash_colorstring default)
  410. BASH_HOSTNAME_COLOR=$(bash_colorstring default)
  411. BASH_SUFFIX_COLOR=$(bash_colorstring default)
  412. BASH_TIMESTAMP_COLOR=$(bash_colorstring default)
  413. fi
  414. ps1_syntax() {
  415. # Default string
  416. export PS1="$BASH_PS1_START_INSERT$(bash_timestamp)$(bash_usercolor)$(bash_hostname)$(bash_folder_separator) \$(bash_foldercolor)\W$(bash_colorstring default)$BASH_PS1_END_INSERT$(bash_suffixsymbol)"
  417. }
  418. if [[ $BASH_PS1_SYNTAX_OVERRIDE == "no" ]]; then
  419. # If we want to use different PS1 variable for local logins...
  420. if [[ $BASH_PS1_DIFFERENT_LOCAL == "yes" ]] && [[ $ENABLE_SERVER_ENV == "yes" ]]; then
  421. # Check if we are local login...
  422. # Returns 0 (true) if we are, otherwise 1 (false)
  423. if [[ ! $(export -p | grep SSH_TTY) ]]; then
  424. export PS1=${BASH_PS1_LOCAL}
  425. else
  426. ps1_syntax
  427. fi
  428. else
  429. ps1_syntax
  430. fi
  431. elif [[ $BASH_PS1_SYNTAX_OVERRIDE == "yes" ]]; then
  432. # User override string
  433. export PS1=${BASH_PS1_SYNTAX_OVERRIDESTR}
  434. else
  435. # Fallback string
  436. export PS1='[\u@\h \W]\$ '
  437. fi
  438. ##############################################################################
  439. # Common messages for sudo checks
  440. #
  441. # Ask password every time for sudo commands?
  442. SUDO_ASKPASS=yes
  443. # Separator
  444. function INFO_SEP() {
  445. # http://wiki.bash-hackers.org/snipplets/print_horizontal_line#a_line_across_the_entire_width_of_the_terminal
  446. printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
  447. }
  448. # Default information printed to user
  449. INFO_MSG="\
  450. $(bash_colorstring orange)\
  451. Privileged permissions required\
  452. $(bash_colorstring default)\
  453. "
  454. #
  455. # If any of the following messages is printed by a command,
  456. # then try the command with sudo prefix
  457. ERROR_MSGS="\
  458. Permission denied|\
  459. Operation not permitted|\
  460. you cannot perform this operation unless you are root|\
  461. You may not view or modify password information for root\
  462. "
  463. #######################################
  464. # Check if the current user belongs to sudo
  465. # or is root
  466. #
  467. sudocheck() {
  468. if [[ $UID -ne 0 ]]; then
  469. if [[ ! $(printf $(groups | grep sudo &> /dev/null)$?) -eq 0 ]]; then
  470. printf "Current user does not have sufficient permissions and does not belong to 'sudo' group.\n"
  471. return 1
  472. else
  473. if [[ $SUDO_ASKPASS == "yes" ]]; then
  474. sudo -k
  475. fi
  476. return 0
  477. fi
  478. else
  479. return 0
  480. fi
  481. }
  482. #######################################
  483. # Execute with sudo if no permissions
  484. # to execute a command otherwise
  485. #
  486. # NOTE: This does not work for nano or cd commands
  487. #
  488. trap 'sudoperms' ERR
  489. function sudoperms() {
  490. # Previous command (ERR) always returns value 1 which is not
  491. # we don't want if the following sudo command succeeds
  492. #
  493. unset PROMPT_COMMAND
  494. local CMD="${BASH_COMMAND}"
  495. local i=0
  496. # WORKAROUND
  497. # rm command has an interactive prompt where
  498. # it asks for confirmation for file deletion
  499. # However, interactive prompt does not work
  500. # very well here, thus we hook --force/-f
  501. # option to the original rm command
  502. #
  503. if [[ "${CMD}" =~ ^rm[[:space:]] ]]; then
  504. CMD=$(printf "${CMD}" | sed -E 's/^rm/rm -f/')
  505. fi
  506. while [[ $i < 1 ]]; do
  507. if [[ $(${CMD} 2>&1 > /dev/null | grep -E "${ERROR_MSGS}") ]]; then
  508. printf "${INFO_MSG}\n"
  509. sudocheck
  510. if [[ $? -eq 0 ]]; then
  511. INFO_SEP
  512. # Execute the failed command with sudo and get its return code
  513. sudo bash -c "${CMD}" && RETCODE
  514. fi
  515. fi
  516. let i++
  517. done
  518. }
  519. #######################################
  520. # If nano doesn't have correct permissions, use sudo
  521. # automatically for it
  522. #
  523. sudonano() {
  524. # Prevent file names having spaces to be splitted up to
  525. # multiple arguments by setting local IFS variable to be
  526. # a newline instead of space
  527. #
  528. local IFS=$'\n'
  529. # Get all input arguments into a new array
  530. local i=0
  531. for arg in "${@}"; do
  532. ARGS[$i]="${arg}"
  533. let i++
  534. done
  535. # If the first argument is not -h or --help, apply other arguments, too
  536. #
  537. if [[ "${1}" != "-h" ]] || [[ "${1}" != "--help" ]]; then
  538. # If the last input argument is a file, delete
  539. # it from the existing ARGS array
  540. # and put it into a new variable FILE .
  541. # Check owner of the file
  542. #
  543. # If no input file is given, treat
  544. # all arguments as options for nano editor
  545. #
  546. if [[ -f "${ARGS[-1]}" ]]; then
  547. # Get full file path (e.g. if user types just
  548. # name of a file in the current folder)
  549. local FILE=$(readlink -f "${ARGS[-1]}")
  550. # Set single quotes around the file name with full path
  551. # This is just for stat command below
  552. #
  553. local FILE=$(printf "${FILE}" | sed "s/\(.*\)\r/'\1'/g")
  554. local OWNER=$(stat -c %u "${FILE}")
  555. # Remove filename from the arguments list since it
  556. # is not actually an argument we want to supply to
  557. # nano. We need to treat the filename in a special
  558. # way unlike other arguments
  559. #
  560. unset 'ARGS[${#ARGS[@]}-1]'
  561. # Add escape prefixes to every whitespace we have
  562. # in the filename because single quotes are
  563. # not well preserved when supplying filename
  564. # to nano command
  565. #
  566. if [[ "${FILE}" =~ [[:space:]] ]]; then
  567. FILE=$(printf "${FILE}" | sed 's/ /\\ /g')
  568. fi
  569. # If arguments were given, put them before
  570. # the filename. If no arguments were given,
  571. # just supply the filename to nano command
  572. #
  573. if [[ -n ${ARGS[*]} ]]; then
  574. local OPTIONS="${ARGS[*]} ${FILE}"
  575. else
  576. local OPTIONS="${FILE}"
  577. fi
  578. else
  579. local OPTIONS="${ARGS[*]}"
  580. fi
  581. else
  582. local OPTIONS="${1}"
  583. fi
  584. if [[ $UID -ne 0 ]]; then
  585. if [[ -v OWNER ]]; then
  586. if [[ $OWNER -ne $UID ]]; then
  587. printf "${INFO_MSG}\n"
  588. sudocheck
  589. if [[ $? -eq 0 ]]; then
  590. INFO_SEP
  591. sudo nano ${OPTIONS}
  592. fi
  593. else
  594. nano ${OPTIONS}
  595. fi
  596. else
  597. nano ${OPTIONS}
  598. fi
  599. else
  600. nano ${OPTIONS}
  601. fi
  602. # In a case of failure (e.g. return code 1)
  603. # we want to get the real code number
  604. # That's why we call RETCODE function
  605. # which returns the right value for
  606. # the previous command
  607. #
  608. RETCODE
  609. # We need to unset PROMPT_COMMAND variable
  610. # after RETCODE function execution
  611. # Otherwise we get false-positive
  612. # return value (return code 0) for
  613. # the previous command, no matter
  614. # whether it succeeded or failed
  615. #
  616. unset PROMPT_COMMAND
  617. }
  618. if [[ $(printf $(which nano &> /dev/null)$?) -eq 0 ]]; then
  619. alias nano='sudonano'
  620. fi
  621. #######################################
  622. # If find doesn't have correct permissions, use sudo
  623. # automatically for it
  624. #
  625. : '
  626. sudofind() {
  627. if [[ ! "${1}" =~ ^-{1,2}[a-z]* ]]; then
  628. if [[ ! -d "${1}" ]]; then
  629. printf "$(bash_colorstring red)Error:$(bash_colorstring default) ${1}: No such directory\n"
  630. return 1
  631. fi
  632. else
  633. find "${1}"
  634. fi
  635. if [[ $UID -ne 0 ]]; then
  636. local i=0
  637. for arg in "${@}"; do
  638. if [[ $arg =~ [[:space:]] ]]; then
  639. arg=\"$arg\"
  640. fi
  641. local ARGS[$i]="${arg}"
  642. let i++
  643. done
  644. local DIRPATH="${ARGS[0]}"
  645. local OWNER_STR=$(stat -c %U "${DIRPATH}")
  646. local USER_STR=$(id -un $UID)
  647. if [[ $OWNER_STR == $USER_STR ]]; then
  648. find "${ARGS[*]}"
  649. else
  650. sudo SUDOARGS="${ARGS[*]}" -u $OWNER_STR bash -c 'find "${SUDOARGS}"'
  651. fi
  652. else
  653. find "${ARGS[*]}"
  654. fi
  655. }
  656. alias find='sudofind'
  657. '
  658. #######################################
  659. # If we don't have access to a directory, check dir owner
  660. # and access the folder as that user with sudo
  661. #
  662. sudocd() {
  663. if [[ -d "${1}" ]]; then
  664. if [[ $UID -ne 0 ]]; then
  665. if [[ $(stat -c %u "${1}") -ne $UID ]]; then
  666. local PERMS=$(stat -c %A "${1}")
  667. if [[ $(echo "${PERMS:9:1}") == "x" ]]; then
  668. cd "${1}"
  669. else
  670. printf "${INFO_MSG}\n"
  671. sudocheck
  672. if [[ $? -eq 0 ]]; then
  673. INFO_SEP
  674. local OWNER=$(stat -c %U "${1}")
  675. printf "Opening $OWNER shell environment\n"
  676. sudo GODIR="${1}" -u $OWNER bash -c 'cd "${GODIR}"; $SHELL'
  677. fi
  678. fi
  679. else
  680. cd "${1}"
  681. fi
  682. else
  683. cd "${1}"
  684. fi
  685. elif [[ -z "${1}" ]]; then
  686. cd "${HOME}"
  687. else
  688. printf "$(bash_colorstring red)Error:$(bash_colorstring default) No such directory\n"
  689. return 1
  690. fi
  691. }
  692. alias cd='sudocd'