Skip to content

Instantly share code, notes, and snippets.

@yudenzel
Last active May 24, 2019 09:01
Show Gist options
  • Select an option

  • Save yudenzel/5437fce66c94b08bfa8a450502d8ea2a to your computer and use it in GitHub Desktop.

Select an option

Save yudenzel/5437fce66c94b08bfa8a450502d8ea2a to your computer and use it in GitHub Desktop.
Bash script to list opened files when lsof command not available
#!/usr/bin/env bash
declare -a SEARCH_PATHS
SEARCH_PATHS[1]=/proc/*
PROC_INDEX=1
while [[ $# -gt 1 ]]; do
case "${1}" in
-p | --pid) SEARCH_PATHS[$PROC_INDEX]="/proc/${2}"; PROC_INDEX=$((PROC_INDEX + 1)); shift 2 ;;
*) ;;
esac
done
# function dirname() { echo "${1%/*}" }
# function basename() { echo "${1##*/}" }
function lsof_main() {
# /proc/2277/fd/8
printf "%6s %-50s %8s %s\n" PID EXECUTABLE FD FILE
for fd_path in $(find ${SEARCH_PATHS[@]} -path '*/fd/*' -maxdepth 2 2>/dev/null |sort -V); do
fd_num="${fd_path##*/}"
proc_dir="${fd_path%/*/*}"
if [[ "${proc_dir}" != "${last_proc_dir}" ]]; then
proc_pid="${proc_dir##*/}"
proc_exe="$(readlink ${proc_dir}/exe)"
last_proc_dir="${proc_dir}"
fi
fd_link="$(readlink ${fd_path} 2>/dev/null)"
if [[ -n "${fd_link}" ]]; then
printf "%6s %-50s %8s %s\n" "${proc_pid}" "${proc_exe}" "${fd_num}" "${fd_link}"
fi
done
}
2>/dev/null lsof_main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment