From e1f1fce3f67e12bcbf397a0546a799d79abe2448 Mon Sep 17 00:00:00 2001 From: Sheldon Lee Date: Mon, 2 Oct 2023 06:51:15 +0800 Subject: [PATCH] Fix script cwd and add fzf fallback --- .config/scripts/libvirt/attach-usb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/.config/scripts/libvirt/attach-usb b/.config/scripts/libvirt/attach-usb index 57d32c1..8328cc5 100755 --- a/.config/scripts/libvirt/attach-usb +++ b/.config/scripts/libvirt/attach-usb @@ -1,4 +1,7 @@ #!/bin/bash +script_location="$(readlink -f "$0")" +cd "$(dirname $script_location)" + if [ "$(id -u)" -ne "0" ]; then pkexec --keep-cwd sh -c "\ WAYLAND_DISPLAY=\"$WAYLAND_DISPLAY\"\ @@ -19,6 +22,14 @@ run_as_user() { echo "$(su "$username" sh -c "source \"/home/$username/.bash_profile\"; $cmd")" } +menu() { + if [ -z "$DISPLAY" ]; then + echo -e "$1" | fzf --prompt="$2" + return 0 + fi + run_as_user "echo -e '$1' | menucmd -p '$2'" +} + csv="$(virsh list | tail --line=+3 | tr ' ' '\n' | uniq | grep -v -e "^[[:space:]]*$" | tr '\n' ',')" vms="$(echo "$csv" | awk -F ',' -v n='3' '{ @@ -31,11 +42,11 @@ for (i = 1; i+1 <= NF; i++) { }')" if [ -z "$vms" ]; then - run_as_user "echo 'No VMs running' | menucmd -p 'Error'" &> /dev/null + menu "No VMs running" "Error" exit 1 fi -vm="$(run_as_user "echo -e '$vms' | menucmd -p VM")" +vm="$(menu "$vms" "VM")" vm_name=$(echo "$vm" | awk '{print $2}') directory="./usb-devices" @@ -43,14 +54,14 @@ directory="./usb-devices" item_list="" for file in "$directory"/*; do - item_list="${item_list}${file}\n" + item_list="${item_list}$(basename $file)\n" done # strip last newline end=${#item_list}-2 item_list=${item_list:0:end} -device="$(run_as_user "echo -e '$item_list' | menucmd")" +device="${directory}/$(menu "$item_list" "Device")" [ -z "$device" ] && exit 1 output=$(virsh attach-device "$vm_name" "$device" 2>&1) && echo "Attached $device to $vm_name"