windows11 wsl2 ubuntu:  Syntax error: "(" unexpected

https://github.com/hitto-hub/scan_and_ssh/issues/2

とあるシェルスクリプトを作って実行したらエラーはいた

実行結果

hitto@hitto:~/scan_and_ssh$ sh scan_and_ssh.sh
Enter IP range to scan (default: 172.29.22.2-254): 192.168.0.2-200
Enter ports to scan (default: 22):
Scanning IP range 192.168.0.2-200 for open ports 22...
The following hosts have open ports 22:
192.168.0.36
192.168.0.200
scan_and_ssh.sh: 37: Syntax error: "(" unexpected
hitto@hitto:~/scan_and_ssh$

37行目で何かのエラーが出たみたい

コード

36 # open_hosts を配列に変換
37 open_hosts_array=($open_hosts)

解決

実行結果

hitto@hitto:~/scan_and_ssh$ ./scan_and_ssh.sh
Enter IP range to scan (default: 172.29.22.2-254): 192.168.0.2-200
Enter ports to scan (default: 22):
Scanning IP range 192.168.0.2-200 for open ports 22...
The following hosts have open ports 22:
192.168.0.36
192.168.0.200
Enter 'f' to use fzf or press Enter to select by number: f
Using fzf to select the host...
Enter the SSH username (default: hitto):
Enter 'f' to use fzf for selecting the SSH private key, or press Enter to input the path manually: f
Using fzf to select the SSH private key...
Attempting to SSH into @192.168.0.36...
(ry

原因

sh->dashにつながっていた

mac のshはbash

win11 wsl2 ubuntuはそうだった

hitto@hitto:~/scan_and_ssh$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Nov 23  2023 /bin/sh -> dash
hitto@hitto:~/scan_and_ssh$ which bash
/usr/bin/bash

macのshはbashらしい

┌───(hitto@hot)-[~]
└─$ /bin/sh --version

GNU bash, version 3.2.57(1)-release (arm64-apple-darwin24)
Copyright (C) 2007 Free Software Foundation, Inc.

そこらへんのubuntuはdashだった

hitto@zako:$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Mar 23  2022 /bin/sh -> dash

dashは配列が使えない

# bashでは有効
# dashではエラーはく
array=(1 2 3)
echo ${array[0]}

解決策

bash scan_and_ssh.sh ./scan_and_ssh.shだと実行できた

/bin/sh → bashにしたらいいかも

そもそも sh ~~~ で実行してはいけないかも

← Go home